Using Java nio to create a subdirectory and file

后端 未结 3 1608
死守一世寂寞
死守一世寂寞 2020-12-30 22:53

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 u

相关标签:
3条回答
  • 2020-12-30 23:07

    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.

    0 讨论(0)
  • 2020-12-30 23:16

    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());
    
    0 讨论(0)
  • 2020-12-30 23:25

    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()))
    
    0 讨论(0)
提交回复
热议问题