4

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

JohnnyO
  • 527
  • 9
  • 21

1 Answers1

6

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 !

JohnnyO
  • 527
  • 9
  • 21
  • 4
    If you want to create a longer path, the method to be used is `Files.createDirectories(file.getParent());`. `createDirectory` will throw an exception if one of the paths is not existing. – kap Feb 11 '16 at 14:49