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:19

The following method should do what you want, just make sure you are checking the return value of 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();
    }
}
查看更多
初与友歌
3楼-- · 2019-01-02 17:20

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

For instance:

Files.createDirectories(Paths.get("/path/to/directory"));
查看更多
无色无味的生活
4楼-- · 2019-01-02 17:21

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

    }
}
查看更多
冷夜・残月
5楼-- · 2019-01-02 17:22
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();
       }

    }
}
查看更多
裙下三千臣
6楼-- · 2019-01-02 17:23

mkdir vs mkdirs


If you want to create a single directory use mkdir

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

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

 new File("/path/directory").mkdirs();
查看更多
无色无味的生活
7楼-- · 2019-01-02 17:23

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