Cannot make file java.io.IOException: No such file or directory

回眸只為那壹抹淺笑 提交于 2019-11-26 23:19:08

问题


I am trying to create a file on the filesystem, but I keep getting this exception:

java.io.IOException: No such file or directory

I have an existing directory, and I am trying to write a file to that 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());
}

Getting exception:

java.io.IOException: No such file or directory
  at java.io.UnixFileSystem.createFileExclusively(Native Method)
  at java.io.File.createNewFile(File.java:883)`

I have write permission to the path, however the file isn't created.


回答1:


Print the full file name out or step through in a debugger. When I get confused by errors like this, it means that my assumptions and expectations don't match reality. Make sure you can see what the path is; it'll help you figure out where you've gone wrong.




回答2:


If the directory ../.foo/bar/ doesn't exist, you can't create a file there, so make sure you create the directory first.

Try something like this:

File f = new File("somedirname1/somedirname2/somefilename");
if (!f.getParentFile().exists())
    f.getParentFile().mkdirs();
if (!f.exists())
    f.createNewFile();



回答3:


Be careful with permissions, it is problably you don't have some of them. You can see it in settings -> apps -> name of the application -> permissions -> active if not.




回答4:


Try with

f.mkdirs() then createNewFile()




回答5:


You may want to use Apache Commons IO's FileUtils.openOutputStream(File) method. It has good Exception messages when something went wrong and also creates necessary parent dirs. If everything was right then you directly get your OutputStream - very neat.

If you just want to touch the file then use FileUtils.touch(File) instead.




回答6:


File.isFile() is false if the file / directory does not exist, so you can't use it to test whether you're trying to create a directory. But that's not the first issue here.

The issue is that the intermediate directories don't exist. You want to call f.mkdirs() first.




回答7:


I got the same problem when using rest-easy. After searching while i figured that this error occured when there is no place to keep temporary files. So in tomcat you can just create tomcat-root/temp folder.




回答8:


i fixed my problem by this code on linux file system

if (!file.exists())
    Files.createFile(file.toPath());


来源:https://stackoverflow.com/questions/7469018/cannot-make-file-java-io-ioexception-no-such-file-or-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!