How to create a new file together with missing parent directories?

后端 未结 3 1798
醉话见心
醉话见心 2020-12-08 09:04

When using

file.createNewFile();

I get the following exception

java.io.IOException: Parent directory of file does not exis         


        
相关标签:
3条回答
  • 2020-12-08 09:20

    Jon's answer works if you are certain that the path string with which you are creating a file includes parent directories, i.e. if you are certain that the path is of the form <parent-dir>/<file-name>.

    If it does not, i.e. it is a relative path of the form <file-name>, then getParentFile() will return null.

    E.g.

    File f = new File("dir/text.txt");
    f.getParentFile().mkdirs();     // works fine because the path includes a parent directory.
    
    File f = new File("text.txt");
    f.getParentFile().mkdirs();     // throws NullPointerException because the parent file is unknown, i.e. `null`.
    

    So if your file path may or may not include parent directories, you are safer with the following code:

    File f = new File(filename);
    if (f.getParentFile() != null) {
      f.getParentFile().mkdirs();
    }
    f.createNewFile();
    
    0 讨论(0)
  • 2020-12-08 09:26

    Have you tried this?

    file.getParentFile().mkdirs();
    file.createNewFile();
    

    I don't know of a single method call that will do this, but it's pretty easy as two statements.

    0 讨论(0)
  • 2020-12-08 09:42

    As of java7, you can also use NIO2 API:

    void createFile() throws IOException {
        Path fp = Paths.get("dir1/dir2/newfile.txt");
        Files.createDirectories(fp.getParent());
        Files.createFile(fp);
    }
    
    0 讨论(0)
提交回复
热议问题