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();
}
这是我的错误。
请输入安装目录的路径。
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)
请帮帮我,这个程序对我来说非常重要。谢谢!
编辑:证明路径存在
再次编辑:我很笨
我真的只是把文件夹命名错误了,不是吗。抱歉浪费你们的时间了,伙计们。 .~.
最佳答案
这很可能是因为给定的父文件夹路径不存在而引起的。解决这个问题的一个简单方法是使用:
file.getParentFile().mkdirs();
File#mkdirs()
本质上会创建该文件的所有父文件夹(如果它们不存在),并且还会将给定文件视为新文件夹。这就是为什么您应该使用 getParentFile().mkdirs();
如果您仍然想创建一个新文件,并且路径的最后部分完好,那就是一个文件!
编辑:只是一个额外的说明,使用 getParentFile()
的好处这样您就不必担心文件路径在运行时被更改或不正确。
您还应该使用input.nextLine().replace("/", File.separator).replace("\\", File.separator);
以防用户输入不遵循操作系统的路径指南。
关于java - 无法创建文件,因为文件不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31876640/