0

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!

4

2 回答 2

2

行 file.mkdirs(); 将创建您尝试创建的文件夹。然后在您的 if(file.mkdir()) 语句中,它试图再次创建文件。编写代码的方式,您将始终得到“未创建”,但该文件夹仍应出现。

于 2013-09-27T22:05:50.323 回答
0

File#mkdirsfalse自行返回。

更好的方法可能是使用更像...

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

在 Windows 7、UAC 和更新的安全模型下,您可能无法写入磁盘上的某些位置,包括Program Files(我们在工作中遇到了这个问题:P)。

更糟糕的是,在Java 6 下,File#canWrite可以返回一个false正数(即,true在您无法写入指定位置时返回)。我们发现的真正奇怪的事情是,您甚至可以尝试写入文件并引发异常...

过去我们所做的是 use File#canWrite,如果返回true,我们实际上将一个文件写入指定位置,检查它是否存在并检查文件的内容。

如果这行得通,那么我们才相信结果。

据我了解,这可能已在 Java 7 中修复...谢谢 Windows:P

于 2013-09-27T23:56:32.203 回答