Search code examples
javanio

NIO getParentFile().mkdir()


Is there a way to create a file and directory in one shot as in below... (Using Java 7 and NIO... Paths and Files static methods ).

where you wouldn't have to type the Path and then file in separate lines ( of code ) ?

File file = new File("Library\\test.txt");
if (file.getParentFile().mkdir()) {
    file.createNewFile();
} else {
    throw new IOException("Failed to create directory " + file.getParent());
}

Basically looking for the equivalent approach to "getParentFile().mkdir()" off the Path ( and file ) entered in Java 7 NIO.

Thx


Solution

  • Actually realized it's accopmplished this way..

    Path file = Paths.get("/Users/jokrasa/Documents/workspace_traffic/javaReviewFeb28/src/TEST/","testy.txt");
            try {
                Files.createDirectory(file.getParent());
                Files.createFile(file);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    

    So you don't have to type it in twice actually...

    Cheers !