如何创建目录/文件夹?

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

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


当前回答

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();
       }

    }
}

其他回答

这是java的一个吸引力,使用短路或'||',测试目录的存在,并为您制作目录

public File checkAndMakeTheDirectory() {
    File theDirectory = new File("/path/directory");
    if (theDirectory.exists() || theDirectory.mkdirs())
        System.out.println("The folder has been created or has been already there");
    return theDirectory;
}

如果If的第一部分为真,它不会运行第二部分,如果第一部分为假,它也会运行第二部分

这种方式为我做一个单一的目录或更多或他们: 需要导入java.io.File; /*输入下面的代码添加目录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");  }

该功能允许在用户的主目录上创建新目录。

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");
    }
}

您可以尝试FileUtils#forceMkdir

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

这个库有很多有用的函数。

下面的方法可以做你想做的事情,只要确保你检查了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();
    }
}