Using Java nio to create a subdirectory and file

2020-02-27 07:35发布

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.

标签: java file nio
2条回答
太酷不给撩
2楼-- · 2020-02-27 08:14

You could do the following:

// Get your Path from the string
Path confFile = Paths.get("./conf/conf.xml"); 
// Get the portion of path that represtents directory structure.  
Path subpath = confFile.subpath(0, confFile.getNameCount() - 1);
// Create all directories recursively
/**
     * Creates a directory by creating all nonexistent parent directories first.
     * Unlike the {@link #createDirectory createDirectory} method, an exception
     * is not thrown if the directory could not be created because it already
     * exists.
     *
*/
Files.createDirectories(subpath.toAbsolutePath()))
查看更多
对你真心纯属浪费
3楼-- · 2020-02-27 08:24

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());
查看更多
登录 后发表回答