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

Dig*_*can 0 java file ioexception

Java将不会让我createNewFile,因为我想创建不存在,对此,文件,这就是为什么我要创建它.这是我的代码片段.

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();
}
Run Code Online (Sandbox Code Playgroud)

这是我的错误.

请输入安装目录的路径.

C:\ Users \用户DigiDuncan \桌面\ 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)
Run Code Online (Sandbox Code Playgroud)

请帮帮我,这个程序对我来说非常重要.谢谢!

编辑:证明路径存在

证明文件路径存在.

再次编辑:我是DUMB

我字面上只是将文件夹命名为错误,不是我.抱歉浪费你的时间,伙计们..〜.

Mom*_*omo 5

这很可能是因为给定的父文件夹路径不存在而导致的.解决这个问题的一个简单方法是使用:

file.getParentFile().mkdirs();
Run Code Online (Sandbox Code Playgroud)

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

编辑:只是一个额外的注释,使用的好方面getParentFile()是你不必担心文件路径在运行时被更改或不正确.

如果input.nextLine().replace("/", File.separator).replace("\\", File.separator);用户输入不符合操作系统的路径指南,您还应该使用它.