无法创建文件,因为文件不存在

Can't create file because file doesn't exist

Java 不允许我创建新文件,因为我要创建的文件不存在,duh,这就是我要创建它的原因。这是我的代码片段。

System.out.println("Please input the path of the install directory.");

System.out.print(">");
installLocation = input.nextLine();

File spreadsheet = new File (installLocation + "diatracker.csv");
File settingsFile = new File (installLocation + "settings.txt");


if ( spreadsheet.exists() )
{
    if ( isValidFile ( spreadsheet.toString() ) )
    {
        //do nothing
    }
    else
    {
        spreadsheet.delete();
        spreadsheet.createNewFile();
    }
}
else
{
    spreadsheet.createNewFile();
}

这是我的错误。

请输入安装目录路径

C:\Users\DigiDuncan\Desktop\DiaTracker\

Exception in thread "main" java.io.IOException: The system cannot find the path specified
    at java.io.WinNTFileSystem.createFileExclusively(Native Method)
    at java.io.File.createNewFile(Unknown Source)
    at DiaTrackApp.firstTimeSetup(DiaTrackApp.java:201)
    at DiaTrackApp.main(DiaTrackApp.java:50)

请帮帮我,这个程序对我来说真的很重要。谢谢!

编辑:证明路径存在

再次编辑:我很笨

我只是把文件夹命名错了,不是吗。抱歉浪费你们的时间,伙计们。 .~.

如果父目录存在,它应该能够创建文件...

可以肯定的是:

// use `\` or `/` or File.separator to be sure
File file = new File("C:\Users\DigiDuncan\Desktop\DiaTracker");
file.mkdirs();// to create parent folders

现在应该可以了。

没有文件夹就无法创建文件...可以查看:

file.exists();// also for folders
file.getParent().exists();// If parent exists, it should be able to create a child (if right permissions)

这很可能是因为给定的父文件夹路径不存在。解决此问题的一种简单方法是使用:

file.getParentFile().mkdirs();

File#mkdirs() 基本上会为该文件创建所有父文件夹(如果它们不存在),并且还会将给定文件视为一个新文件夹。这就是为什么你应该使用 getParentFile().mkdirs(); 如果你仍然想创建一个新文件并且路径的最后一部分很好,一个文件!

编辑:额外说明一下,使用 getParentFile() 的好处是您不必担心文件路径在运行时被更改或不正确。

如果用户输入不遵循 OS 的路径准则,您还应该使用 input.nextLine().replace("/", File.separator).replace("\", File.separator);