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

后端 未结 3 1797
醉话见心
醉话见心 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: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);
    }
    

提交回复
热议问题