PlasmaFighter_
PlasmaFighter_

Reputation: 3

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

Upvotes: 0

Views: 453

Answers (2)

Hugues M.
Hugues M.

Reputation: 20467

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.

Upvotes: 1

Michael
Michael

Reputation: 44090

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.

Upvotes: 1

Related Questions