Rincewind
Rincewind

Reputation: 412

Trouble with creating a new folder in Windows using Java

Established Fact: application does not need to be platform independent.

I have been sitting here for a while and I don't know why this is causing me so much of an issue. What I want to do is this:

1) check to see if a file exists
2) if it doesn't exist, create it and then let me know
3) if it does exist, don't try to write over it anyway, just do nothing and let me know

String pathToChange = "C:/Program Files/WOTA".replace("/", "\\");
    JOptionPane.showMessageDialog(rootPane, pathToChange);
    File file = new File(pathToChange);
    if (!file.exists()) {
        file.mkdirs();
        if (file.mkdir()) {JOptionPane.showMessageDialog(rootPane, "C:/Program            Files/WOTA was created."); }
        else { JOptionPane.showMessageDialog(rootPane, "Did not create.");
    }

    }

I don't know why but this is giving me a lot of trouble but it is. Oh, and you'll notice that I am having a JOptionPanel (Dialog) pop up with the file name that it is trying to create so that I know what is getting handed off is correct.

Can anyone kindly point out why this is not working and what I will need to do to make it work. More importantly, since I am a prideful bastard and I don't like others doing my work for me, please tell me why it wouldn't work.

Btw, I am building all of this in NetBeans.

Thank you!

Upvotes: 0

Views: 611

Answers (2)

MadProgrammer
MadProgrammer

Reputation: 347234

File#mkdirs will return false on it's own accord.

A better approach might be to use something more like...

if (!file.exists() && !file.mkdirs()) {
    // Can not make the directory
} else {
    // Directories exists or was created
}

Under Windows 7, the UAC and updated security model, you may not be able to write to certain locations on the disk, including Program Files (we've had this issue at work :P).

Even worse, under Java 6, File#canWrite can return a false positive (ie, return true when you can't write to the specified location). The really bizarre thing we found was that you could even try and write to a file with it raising an exception...

What we've done in the past is use File#canWrite, if returns true, we actually write a file to the specified location, check to see if it exists and check the contents of the file.

If this works, only then do we trust the result.

As I understand it, this may have being fixed in Java 7...Thank you Windows :P

Upvotes: 0

jhnewkirk
jhnewkirk

Reputation: 87

The line file.mkdirs(); will create the folder that you are trying to create. Then in your if(file.mkdir()) statement, it is attempting to create the file again. The way the code is written, you will always get the "Did not create" but the folder should still appear.

Upvotes: 2

Related Questions