How to create a folder in Java?

2019-01-04 12:04发布

How can I create an empty folder in Java?

8条回答
戒情不戒烟
2楼-- · 2019-01-04 12:13
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();
} 
查看更多
Lonely孤独者°
3楼-- · 2019-01-04 12:15

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!!!");
            }
        }
    }
}
查看更多
Explosion°爆炸
4楼-- · 2019-01-04 12:28

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.

查看更多
Rolldiameter
5楼-- · 2019-01-04 12:29

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();
查看更多
唯我独甜
6楼-- · 2019-01-04 12:32

Call File.mkdir, like this:

new File(path).mkdir();
查看更多
The star\"
7楼-- · 2019-01-04 12:32

Use mkdir():

new File('/path/to/folder').mkdir();
查看更多
登录 后发表回答