Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Java nio to create a subdirectory and file

Tags:

java

file

nio

I'm creating a simple program that will try to read in "conf/conf.xml" from disk, but if this file or dir doesn't exist will instead create them.

I can do this using the following code:

    // create subdirectory path
    Path confDir = Paths.get("./conf"); 

    // create file-in-subdirectory path
    Path confFile = Paths.get("./conf/conf.xml"); 

    // if the sub-directory doesn't exist then create it
    if (Files.notExists(confDir)) { 
        try { Files.createDirectory(confDir); }
        catch (Exception e ) { e.printStackTrace(); }
    }

    // if the file doesn't exist then create it
    if (Files.notExists(confFile)) {
        try { Files.createFile(confFile); }
        catch (Exception e ) { e.printStackTrace(); }
    }

My questions is if this really the most elegant way to do this? It seems superflous to need to create two Paths simple to create a new file in a new subdirectory.

like image 376
user3341332 Avatar asked Feb 22 '14 17:02

user3341332


People also ask

How do you create a subdirectory in Java?

You can just use file. mkdirs() , it will create sub-directory.

How do I create a directory and file in Java?

In Java, we can use the File object to create a new folder or directory. The File class of Java provide a way through which we can make or create a directory or folder. We use the mkdir() method of the File class to create a new folder.

How do you create a directory in Java?

In Java, the mkdir() function is used to create a new directory. This method takes the abstract pathname as a parameter and is defined in the Java File class. mkdir() returns true if the directory is created successfully; else, it returns false​.


2 Answers

You could declare your confFile as File instead of Path. Then you can use confFile.getParentFile().mkdirs();, see example below:

// ...

File confFile = new File("./conf/conf.xml"); 
confFile.getParentFile().mkdirs();

// ...

Or, using your code as is, you can use:

Files.createDirectories(confFile.getParent());
like image 55
Marko Gresak Avatar answered Oct 18 '22 20:10

Marko Gresak


You can create directory and file in one code line:

Files.createFile(Files.createDirectories(confDir).resolve(confFile.getFileName()))

Files.createDirectories(confDir) will not throw an exception if the folder already exists and returns Path in any case.

like image 4
Valeriy K. Avatar answered Oct 18 '22 21:10

Valeriy K.