java - 无法生成文件 java.io.IOException : No such file or directory

标签 java file ioexception

我正在尝试在文件系统上创建一个文件,但我不断收到此异常:

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/

相关文章:

java - JFrame 立即关闭

java - 在本地网络上查找服务器 ip 地址

java - 用 % 处理溢出

java - Java中如何将两个文件夹文件合并为一个

javascript - 如何从 Javascript 获取 File 对象

java - 无法将 String[] 对象放入我的队列<String[]>

java - Java从上到下读取文件夹中的文件

android - IOException BufferedInputStream 在 HTC 中关闭

android - 在Interceptor中抛出IOException会导致Retrofit崩溃

java - weka 中的行过早结束