java - 系统找不到指定的路径

标签 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 异常,它表示系统找不到指定的路径,并且无法理解为什么?

最佳答案

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

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/

相关文章:

c# - 目录树的倒数第二层

java - WSServletContextLi stener context在使用 cobertura 部署 war 时被破坏

java - 使用适配器与代理与多个提供商集成

python - Twisted python 的问题 - 发送二进制数据

c - 使用文件系统的最佳方式?

c# - WPF IOException 找不到资源

java - Azure Android Blob 上传 IOException

android - java.lang.RuntimeException : Parcelable encountered IOException writing serializable object 错误

java - 方法与类型中的另一个方法具有相同的删除

java - 如果重新打开应用程序,SharedPreferences 不会保存