How to create a directory in Java?

2019-01-02 16:36发布

How do I create Directory/folder?

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

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

17条回答
流年柔荑漫光年
2楼-- · 2019-01-02 17:27
  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.

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

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

查看更多
浮光初槿花落
3楼-- · 2019-01-02 17:27

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() 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.

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

查看更多
泪湿衣
4楼-- · 2019-01-02 17:31

You can try FileUtils#forceMkdir

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

This library have a lot of useful functions.

查看更多
泛滥B
5楼-- · 2019-01-02 17:31

For java 7 and up:

Path path = Paths.get("/your/path/string");
if(!Files.exists(path)) {
    try {
      Files.createDirectories(path);
    } catch (IOException e) {
      e.printStackTrace();
    }
}
查看更多
高级女魔头
6楼-- · 2019-01-02 17:31

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 */

    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");  }
查看更多
登录 后发表回答