我正在尝试使用 Java 中的 createNewFile()
方法创建一个新文件:
File savegame = new File(System.getenv("APPDATA") + File.separator + "Game" + File.separator + "test" + ".ser");
try
{
savegame.createNewFile();
}
catch(IOException exc)
{
exc.printStackTrace();
}
但是我收到一个 IOException 异常,它表示系统找不到指定的路径,并且无法理解为什么?
最佳答案
确保要在其中创建文件的目录存在。要在创建文件之前创建目录,可以执行以下操作:
File savegame = new File(System.getenv("APPDATA") + File.separator + "Game" + File.separator + "test" + ".ser");
try
{
savegame.getParentFile().mkdirs(); // create parent directory
savegame.createNewFile();
}
catch(IOException exc)
{
exc.printStackTrace();
}
来自File#mkdirs()
的文档:
Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories. Note that if this operation fails it may have succeeded in creating some of the necessary parent directories.
关于java - 系统找不到指定的路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29446369/