简体   繁体   中英

Trouble with creating a new folder in Windows using Java

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 it wouldn't work. 它不起作用。

Btw, I am building all of this in NetBeans.

Thank you!

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.

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

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