我正在尝试在文件系统上创建一个文件,但我不断收到此异常:
java.io.IOException: No such file or directory
我有一个现有目录,我正在尝试将文件写入该目录。
// I have also tried this below, but get same error
// new File(System.getProperty("user.home") + "/.foo/bar/" + fileName);
File f = new File(System.getProperty("user.home") + "/.foo/bar/", fileName);
if (f.exists() && !f.canWrite())
throw new IOException("Kan ikke skrive til filsystemet " + f.getAbsolutePath());
if (!f.isFile()) {
f.createNewFile(); // Exception here
} else {
f.setLastModified(System.currentTimeMillis());
}
获取异常:
java.io.IOException: No such file or directory
at java.io.UnixFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(File.java:883)`
我对路径有写权限,但是没有创建文件。
最佳答案
如果目录 ../.foo/bar/
不存在,则无法在其中创建文件,因此请确保先创建目录。
试试这样的:
File f = new File("somedirname1/somedirname2/somefilename");
if (!f.getParentFile().exists())
f.getParentFile().mkdirs();
if (!f.exists())
f.createNewFile();
关于java - 无法生成文件 java.io.IOException : No such file or directory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7469018/