How to create a folder in Java?

匆匆过客 提交于 2019-11-26 04:49:20

问题


How can I create an empty folder in Java?


回答1:


File f = new File("C:\\TEST");
try{
    if(f.mkdir()) { 
        System.out.println("Directory Created");
    } else {
        System.out.println("Directory is not created");
    }
} catch(Exception e){
    e.printStackTrace();
} 



回答2:


Call File.mkdir, like this:

new File(path).mkdir();



回答3:


With Java 7 and newer you can use the static Files.createDirectory() method of the java.nio.file.Files class along with Paths.get.

Files.createDirectory(Paths.get("/path/to/folder"));

The method Files.createDirectories() also creates parent directories if these do not exist.




回答4:


Use mkdir():

new File('/path/to/folder').mkdir();



回答5:


Use the mkdir method on the File class:

http://java.sun.com/j2se/1.4.2/docs/api/java/io/File.html#mkdir%28%29




回答6:


Using Java 8:

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

Same:

new File("/path/to/folder").mkdirs();

Or

Files.createDirectory(Paths.get("/path/to/folder"));

Same:

new File("/path/to/folder").mkdir();



回答7:


Better to use mkdirs as:

new File("dirPath/").mkdirs();

mkdirs: also create parent directories if these do not exist.

ps: don't forget the ending / that shows explicitly you want to make a directory.




回答8:


The following code would be helpful for the creation of single or multiple directories:

import java.io.File;

public class CreateSingleOrMultipleDirectory{
    public static void main(String[] args) {
//To create single directory
        File file = new File("D:\\Test");
        if (!file.exists()) {
            if (file.mkdir()) {
                System.out.println("Folder/Directory is created successfully");
            } else {
                System.out.println("Directory/Folder creation failed!!!");
            }
        }
//To create multiple directories
        File files = new File("D:\\Test1\\Test2\\Test3");
        if (!files.exists()) {
            if (files.mkdirs()) {
                System.out.println("Multiple directories are created successfully");
            } else {
                System.out.println("Failed to create multiple directories!!!");
            }
        }
    }
}


来源:https://stackoverflow.com/questions/3024002/how-to-create-a-folder-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!