简体   繁体   中英

How do I create an empty folder in java?

The problem I am having is that when I attempt to create the folder, it doesn't create. It might have something to do with the directory, but honestly I don't know. I tried using this:

File f = new File(javax.swing.filechooser.FileSystemView.getFileSystemView().getHomeDirectory() + "/Levels/First Folder/Levels");
    try{
        if(f.mkdir()) { 
            System.out.println("Directory Created");
        } else {
            System.out.println("Directory is not created");
        }
    } catch(Exception e){
        e.printStackTrace();
    } 

But it didn't work for me.

And this is the directory I put in the File, but I want the program to work on any computer: C:\\Users\\(My name)\\Desktop\\Levels\\First Folder\\Levels

You said only the Desktop directory exists, so you'll need to use mkdirs to construct the whole directory tree:

File f = new File(javax.swing.filechooser.FileSystemView.getFileSystemView().getHomeDirectory() + "/Levels/First Folder/Levels");
try{
    if(f.mkdirs()) { //< plural
        System.out.println("Directory Created");

Keep in mind: you may want to check whether this directory exists before you try to create it, as it presumably isn't an error and is permissible to continue if your program has created it once before.

Recommending Files.createDirectories() instead of File.mkdirs() because handling errors is more straightforward.

Thus: Files.createDirectories(Paths.get(System.getProperty("user.home"), "/Levels/First Folder/Levels"));

With mkdirs() it is difficult to determine if it failed, why it failed, or if it did not create the directory because it already existed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM