Create a directory if it does not exist and then create the files in that directory as well

前端 未结 7 1234
礼貌的吻别
礼貌的吻别 2020-12-12 14:36

Condition is if directory exists it has to create files in that specific directory with out creating a new directory.

The below code only creating a file with new di

7条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-12 15:16

    I would suggest the following for Java8+.

    /**
     * Creates a File if the file does not exist, or returns a
     * reference to the File if it already exists.
     */
    private File createOrRetrieve(final String target) throws IOException{
    
        final Path path = Paths.get(target);
    
        if(Files.notExists(path)){
            LOG.info("Target file \"" + target + "\" will be created.");
            return Files.createFile(Files.createDirectories(path)).toFile();
        }
        LOG.info("Target file \"" + target + "\" will be retrieved.");
        return path.toFile();
    }
    
    /**
     * Deletes the target if it exists then creates a new empty file.
     */
    private File createOrReplaceFileAndDirectories(final String target) throws IOException{
    
        final Path path = Paths.get(target);
        // Create only if it does not exist already
        Files.walk(path)
            .filter(p -> Files.exists(p))
            .sorted(Comparator.reverseOrder())
            .peek(p -> LOG.info("Deleted existing file or directory \"" + p + "\"."))
            .forEach(p -> {
                try{
                    Files.createFile(Files.createDirectories(p));
                }
                catch(IOException e){
                    throw new IllegalStateException(e);
                }
            });
    
        LOG.info("Target file \"" + target + "\" will be created.");
    
        return Files.createFile(
            Files.createDirectories(path)
        ).toFile();
    }
    

提交回复
热议问题