如何在Java中创建一个目录?

时间:2021-09-07 16:23:50

How do I create Directory/folder?

如何创建目录/文件夹?

Once I have tested System.getProperty("user.home");

一旦我测试了System.getProperty("user.home");

I have to create a directory (directory name "new folder" ) if and only if new folder does not exist.

如果且仅当新文件夹不存在时,我必须创建一个目录(目录名“新文件夹”)。

18 个解决方案

#1


333  

After ~7 year, I will update it to better approach which is suggested by Bozho.

7年后,我将更新它,以更好的方法,这是由Bozho提出的。

new File("/path/directory").mkdirs();

Deprecated:

弃用:

File theDir = new File("new folder");

// if the directory does not exist, create it
if (!theDir.exists()) {
    System.out.println("creating directory: " + theDir.getName());
    boolean result = false;

    try{
        theDir.mkdir();
        result = true;
    } 
    catch(SecurityException se){
        //handle it
    }        
    if(result) {    
        System.out.println("DIR created");  
    }
}

#2


411  

new File("/path/directory").mkdirs();

Here "directory" is the name of the directory you want to create/exist.

这里的“目录”是您想要创建/存在的目录的名称。

#3


103  

With Java 7, you can use Files.createDirectories().

使用Java 7,您可以使用files.createdirectory()。

For instance:

例如:

Files.createDirectories(Paths.get("/path/to/directory"));

#4


36  

You can try FileUtils#forceMkdir

你可以试试FileUtils # forceMkdir

FileUtils.forceMkdir("/path/directory");

This library have a lot of useful functions.

这个图书馆有许多有用的功能。

#5


21  

mkdir vs mkdirs


If you want to create a single directory use mkdir

如果您想创建单个目录,请使用mkdir。

new File("/path/directory").mkdir();

If you want to create a hierarchy of folder structure use mkdirs

如果要创建文件夹结构的层次结构,请使用mkdirs。

 new File("/path/directory").mkdirs();

#6


16  

  1. Create a single directory.

    创建一个目录。

    new File("C:\\Directory1").mkdir();
    
  2. Create a directory named “Directory2 and all its sub-directories “Sub2″ and “Sub-Sub2″ together.

    创建一个名为“Directory2”的目录,以及它的所有子目录“和”subsub2“一起”。

    new File("C:\\Directory2\\Sub2\\Sub-Sub2").mkdirs()
    

Source: this perfect tuto , you find also an example of use.

来源:这个完美的tuto,你也可以找到一个使用的例子。

#7


6  

The following method should do what you want, just make sure you are checking the return value of mkdir() / mkdirs()

下面的方法应该做您想做的事情,只需要检查mkdir() / mkdirs()的返回值

private void createUserDir(final String dirName) throws IOException {
    final File homeDir = new File(System.getProperty("user.home"));
    final File dir = new File(homeDir, dirName);
    if (!dir.exists() && !dir.mkdirs()) {
        throw new IOException("Unable to create " + dir.getAbsolutePath();
    }
}

#8


5  

For java 7 and up:

对于java 7和up:

Path path = Paths.get("/your/path/string");
if(!Files.exists(path)) {
    try {
      Files.createDirectories(path);
    } catch (IOException e) {
      e.printStackTrace();
    }
}

#9


4  

Though this question has been answered. I would like to put something extra, i.e. if there is a file exist with the directory name that you are trying to create than it should prompt an error. For future visitors.

虽然这个问题已经得到解答。我想要添加一些额外的东西,即如果有一个文件存在,并且您正在尝试创建的目录名,而不是它应该提示一个错误。为未来的游客。

public static void makeDir()
{
    File directory = new File(" dirname ");
    if (directory.exists() && directory.isFile())
    {
        System.out.println("The dir with name could not be" +
        " created as it is a normal file");
    }
    else
    {
        try
        {
            if (!directory.exists())
            {
                directory.mkdir();
            }
            String username = System.getProperty("user.name");
            String filename = " path/" + username + ".txt"; //extension if you need one

        }
        catch (IOException e)
        {
            System.out.println("prompt for error");
        }
    }
}

#10


3  

Just wanted to point out to everyone calling File.mkdir() or File.mkdirs() to be careful the File object is a directory and not a file. For example if you call mkdirs() for the path /dir1/dir2/file.txt, it will create a folder with the name file.txt which is probably not what you wanted. If you are creating a new file and also want to automatically create parent folders you can do something like this:

只是想指出每个调用File.mkdir()或File.mkdirs()的每个人都要小心,文件对象是一个目录而不是一个文件。例如,如果您调用路径/dir1/dir2/文件的mkdirs()。txt,它将创建一个文件夹与名称文件。txt可能不是你想要的。如果您正在创建一个新文件,并希望自动创建父文件夹,您可以这样做:

            File file = new File(filePath);
            if (file.getParentFile() != null) {
                file.getParentFile().mkdirs();
            }

#11


3  

Neat and clean:

整洁:

import java.io.File;

public class RevCreateDirectory {

    public void revCreateDirectory() {
        //To create single directory/folder
        File file = new File("D:\\Directory1");
        if (!file.exists()) {
            if (file.mkdir()) {
                System.out.println("Directory is created!");
            } else {
                System.out.println("Failed to create directory!");
            }
        }
        //To create multiple directories/folders
        File files = new File("D:\\Directory2\\Sub2\\Sub-Sub2");
        if (!files.exists()) {
            if (files.mkdirs()) {
                System.out.println("Multiple directories are created!");
            } else {
                System.out.println("Failed to create multiple directories!");
            }
        }

    }
}

#12


2  

try with this.

试一试。

import java.io.File;

public class MakingDirectory {
 public static void main(String[] args) {
      String s="d:\\msreddy\\sample1";
      File file=new File(s);
      file.mkdirs();
}
}

for more information see this.

有关更多信息,请参见本文。

#13


2  

Well to create Directory/folder in java we have two methods

要在java中创建目录/文件夹,我们有两种方法。

Here makedirectory method creates single directory if it does not exist.

如果不存在,makedirectory方法将创建单个目录。

File dir = new File("path name");
boolean isCreated = dir.mkdir();

And

File dir = new File("path name");
boolean isCreated = dir.mkdirs();

Here makedirectories method will create all directories that are missing in the path which the file object represent.

这里makedirectory方法将创建文件对象所表示的路径中丢失的所有目录。

For example refer link below (explained very well). Hope it helps!! http://www.flowerbrackets.com/create-directory-java-program/

例如下面的链接(解释得很好)。希望它帮助! !http://www.flowerbrackets.com/create-directory-java-program/

#14


1  

This the way work for me do one single directory or more or them: need to import java.io.File;
/*enter the code below to add a diectory dir1 or check if exist dir1, if does not, so create it and same with dir2 and dir3 */

这是我的工作方式,我只做一个目录或者更多,或者它们:需要导入java.io.File;/*输入下面的代码,添加一个diectory dir1,或者检查是否存在dir1,如果没有,那么创建它,同样使用dir2和dir3 */。

    File filed = new File("C:\\dir1");
    if(!filed.exists()){  if(filed.mkdir()){ System.out.println("directory is created"); }} else{ System.out.println("directory exist");  }

    File filel = new File("C:\\dir1\\dir2");
    if(!filel.exists()){  if(filel.mkdir()){ System.out.println("directory is created");   }} else{ System.out.println("directory exist");  }

    File filet = new File("C:\\dir1\\dir2\\dir3");
    if(!filet.exists()){  if(filet.mkdir()){ System.out.println("directory is  created"); }}  else{ System.out.println("directory exist");  }

#15


0  

This function allows you to create a directory on the user home directory.

这个函数允许您在用户主目录上创建一个目录。

private static void createDirectory(final String directoryName) {
    final File homeDirectory = new File(System.getProperty("user.home"));
    final File newDirectory = new File(homeDirectory, directoryName);
    if(!newDirectory.exists()) {
        boolean result = newDirectory.mkdir();

        if(result) {
            System.out.println("The directory is created !");
        }
    } else {
        System.out.println("The directory already exist");
    }
}

#16


0  

if you want to be sure its created then this:

如果你想确定它的创建,那么

final String path = "target/logs/";
final File logsDir = new File(path);
final boolean logsDirCreated = logsDir.mkdir();
if (!logsDirCreated) {
    final boolean logsDirExists = logsDir.exists();
    assertThat(logsDirExists).isTrue();
}

beacuse mkDir() returns a boolean, and findbugs will cry for it if you dont use the variable. Also its not nice...

因为mkDir()返回一个布尔值,如果您不使用该变量,findbugs将为它哭泣。也不是好…

mkDir() returns only true if mkDir() creates it. If the dir exists, it returns false, so to verify the dir you created, only call exists() if mkDir() return false.

mkDir()只返回true,如果mkDir()创建它。如果该dir存在,它将返回false,因此要验证您创建的dir,只有在mkDir()返回false时才调用exists()。

assertThat() will checks the result and fails if exists() returns false. ofc you can use other things to handle the uncreated directory.

assertThat()将检查结果,如果存在()返回false,则失败。ofc可以使用其他的东西来处理未创建的目录。

#17


-2  

public class Test1 {
    public static void main(String[] args)
    {
       String path = System.getProperty("user.home");
       File dir=new File(path+"/new folder");
       if(dir.exists()){
           System.out.println("A folder with name 'new folder' is already exist in the path "+path);
       }else{
           dir.mkdir();
       }

    }
}

#18


-7  

You can also refer makdir() function for creating a new directory in a folder where you want.

您还可以引用makdir()函数来在您想要的文件夹中创建一个新目录。

#1


333  

After ~7 year, I will update it to better approach which is suggested by Bozho.

7年后,我将更新它,以更好的方法,这是由Bozho提出的。

new File("/path/directory").mkdirs();

Deprecated:

弃用:

File theDir = new File("new folder");

// if the directory does not exist, create it
if (!theDir.exists()) {
    System.out.println("creating directory: " + theDir.getName());
    boolean result = false;

    try{
        theDir.mkdir();
        result = true;
    } 
    catch(SecurityException se){
        //handle it
    }        
    if(result) {    
        System.out.println("DIR created");  
    }
}

#2


411  

new File("/path/directory").mkdirs();

Here "directory" is the name of the directory you want to create/exist.

这里的“目录”是您想要创建/存在的目录的名称。

#3


103  

With Java 7, you can use Files.createDirectories().

使用Java 7,您可以使用files.createdirectory()。

For instance:

例如:

Files.createDirectories(Paths.get("/path/to/directory"));

#4


36  

You can try FileUtils#forceMkdir

你可以试试FileUtils # forceMkdir

FileUtils.forceMkdir("/path/directory");

This library have a lot of useful functions.

这个图书馆有许多有用的功能。

#5


21  

mkdir vs mkdirs


If you want to create a single directory use mkdir

如果您想创建单个目录,请使用mkdir。

new File("/path/directory").mkdir();

If you want to create a hierarchy of folder structure use mkdirs

如果要创建文件夹结构的层次结构,请使用mkdirs。

 new File("/path/directory").mkdirs();

#6


16  

  1. Create a single directory.

    创建一个目录。

    new File("C:\\Directory1").mkdir();
    
  2. Create a directory named “Directory2 and all its sub-directories “Sub2″ and “Sub-Sub2″ together.

    创建一个名为“Directory2”的目录,以及它的所有子目录“和”subsub2“一起”。

    new File("C:\\Directory2\\Sub2\\Sub-Sub2").mkdirs()
    

Source: this perfect tuto , you find also an example of use.

来源:这个完美的tuto,你也可以找到一个使用的例子。

#7


6  

The following method should do what you want, just make sure you are checking the return value of mkdir() / mkdirs()

下面的方法应该做您想做的事情,只需要检查mkdir() / mkdirs()的返回值

private void createUserDir(final String dirName) throws IOException {
    final File homeDir = new File(System.getProperty("user.home"));
    final File dir = new File(homeDir, dirName);
    if (!dir.exists() && !dir.mkdirs()) {
        throw new IOException("Unable to create " + dir.getAbsolutePath();
    }
}

#8


5  

For java 7 and up:

对于java 7和up:

Path path = Paths.get("/your/path/string");
if(!Files.exists(path)) {
    try {
      Files.createDirectories(path);
    } catch (IOException e) {
      e.printStackTrace();
    }
}

#9


4  

Though this question has been answered. I would like to put something extra, i.e. if there is a file exist with the directory name that you are trying to create than it should prompt an error. For future visitors.

虽然这个问题已经得到解答。我想要添加一些额外的东西,即如果有一个文件存在,并且您正在尝试创建的目录名,而不是它应该提示一个错误。为未来的游客。

public static void makeDir()
{
    File directory = new File(" dirname ");
    if (directory.exists() && directory.isFile())
    {
        System.out.println("The dir with name could not be" +
        " created as it is a normal file");
    }
    else
    {
        try
        {
            if (!directory.exists())
            {
                directory.mkdir();
            }
            String username = System.getProperty("user.name");
            String filename = " path/" + username + ".txt"; //extension if you need one

        }
        catch (IOException e)
        {
            System.out.println("prompt for error");
        }
    }
}

#10


3  

Just wanted to point out to everyone calling File.mkdir() or File.mkdirs() to be careful the File object is a directory and not a file. For example if you call mkdirs() for the path /dir1/dir2/file.txt, it will create a folder with the name file.txt which is probably not what you wanted. If you are creating a new file and also want to automatically create parent folders you can do something like this:

只是想指出每个调用File.mkdir()或File.mkdirs()的每个人都要小心,文件对象是一个目录而不是一个文件。例如,如果您调用路径/dir1/dir2/文件的mkdirs()。txt,它将创建一个文件夹与名称文件。txt可能不是你想要的。如果您正在创建一个新文件,并希望自动创建父文件夹,您可以这样做:

            File file = new File(filePath);
            if (file.getParentFile() != null) {
                file.getParentFile().mkdirs();
            }

#11


3  

Neat and clean:

整洁:

import java.io.File;

public class RevCreateDirectory {

    public void revCreateDirectory() {
        //To create single directory/folder
        File file = new File("D:\\Directory1");
        if (!file.exists()) {
            if (file.mkdir()) {
                System.out.println("Directory is created!");
            } else {
                System.out.println("Failed to create directory!");
            }
        }
        //To create multiple directories/folders
        File files = new File("D:\\Directory2\\Sub2\\Sub-Sub2");
        if (!files.exists()) {
            if (files.mkdirs()) {
                System.out.println("Multiple directories are created!");
            } else {
                System.out.println("Failed to create multiple directories!");
            }
        }

    }
}

#12


2  

try with this.

试一试。

import java.io.File;

public class MakingDirectory {
 public static void main(String[] args) {
      String s="d:\\msreddy\\sample1";
      File file=new File(s);
      file.mkdirs();
}
}

for more information see this.

有关更多信息,请参见本文。

#13


2  

Well to create Directory/folder in java we have two methods

要在java中创建目录/文件夹,我们有两种方法。

Here makedirectory method creates single directory if it does not exist.

如果不存在,makedirectory方法将创建单个目录。

File dir = new File("path name");
boolean isCreated = dir.mkdir();

And

File dir = new File("path name");
boolean isCreated = dir.mkdirs();

Here makedirectories method will create all directories that are missing in the path which the file object represent.

这里makedirectory方法将创建文件对象所表示的路径中丢失的所有目录。

For example refer link below (explained very well). Hope it helps!! http://www.flowerbrackets.com/create-directory-java-program/

例如下面的链接(解释得很好)。希望它帮助! !http://www.flowerbrackets.com/create-directory-java-program/

#14


1  

This the way work for me do one single directory or more or them: need to import java.io.File;
/*enter the code below to add a diectory dir1 or check if exist dir1, if does not, so create it and same with dir2 and dir3 */

这是我的工作方式,我只做一个目录或者更多,或者它们:需要导入java.io.File;/*输入下面的代码,添加一个diectory dir1,或者检查是否存在dir1,如果没有,那么创建它,同样使用dir2和dir3 */。

    File filed = new File("C:\\dir1");
    if(!filed.exists()){  if(filed.mkdir()){ System.out.println("directory is created"); }} else{ System.out.println("directory exist");  }

    File filel = new File("C:\\dir1\\dir2");
    if(!filel.exists()){  if(filel.mkdir()){ System.out.println("directory is created");   }} else{ System.out.println("directory exist");  }

    File filet = new File("C:\\dir1\\dir2\\dir3");
    if(!filet.exists()){  if(filet.mkdir()){ System.out.println("directory is  created"); }}  else{ System.out.println("directory exist");  }

#15


0  

This function allows you to create a directory on the user home directory.

这个函数允许您在用户主目录上创建一个目录。

private static void createDirectory(final String directoryName) {
    final File homeDirectory = new File(System.getProperty("user.home"));
    final File newDirectory = new File(homeDirectory, directoryName);
    if(!newDirectory.exists()) {
        boolean result = newDirectory.mkdir();

        if(result) {
            System.out.println("The directory is created !");
        }
    } else {
        System.out.println("The directory already exist");
    }
}

#16


0  

if you want to be sure its created then this:

如果你想确定它的创建,那么

final String path = "target/logs/";
final File logsDir = new File(path);
final boolean logsDirCreated = logsDir.mkdir();
if (!logsDirCreated) {
    final boolean logsDirExists = logsDir.exists();
    assertThat(logsDirExists).isTrue();
}

beacuse mkDir() returns a boolean, and findbugs will cry for it if you dont use the variable. Also its not nice...

因为mkDir()返回一个布尔值,如果您不使用该变量,findbugs将为它哭泣。也不是好…

mkDir() returns only true if mkDir() creates it. If the dir exists, it returns false, so to verify the dir you created, only call exists() if mkDir() return false.

mkDir()只返回true,如果mkDir()创建它。如果该dir存在,它将返回false,因此要验证您创建的dir,只有在mkDir()返回false时才调用exists()。

assertThat() will checks the result and fails if exists() returns false. ofc you can use other things to handle the uncreated directory.

assertThat()将检查结果,如果存在()返回false,则失败。ofc可以使用其他的东西来处理未创建的目录。

#17


-2  

public class Test1 {
    public static void main(String[] args)
    {
       String path = System.getProperty("user.home");
       File dir=new File(path+"/new folder");
       if(dir.exists()){
           System.out.println("A folder with name 'new folder' is already exist in the path "+path);
       }else{
           dir.mkdir();
       }

    }
}

#18


-7  

You can also refer makdir() function for creating a new directory in a folder where you want.

您还可以引用makdir()函数来在您想要的文件夹中创建一个新目录。