系统找不到指定的路径

时间:2015-04-04 12:24:15

标签: java file ioexception

我正在尝试使用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,它说系统找不到指定的路径而无法理解为什么?

1 个答案:

答案 0 :(得分:1)

确保存在应创建文件的目录。要在创建文件之前创建目录,可以执行以下操作:

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()的文档:

  

创建此抽象路径名所指定的目录,包括任何必要但不存在的父目录。请注意,如果此操作失败,则可能已成功创建了一些必要的父目录。

相关问题