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

前端 未结 7 1232
礼貌的吻别
礼貌的吻别 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:03

    If you create a web based application, the better solution is to check the directory exists or not then create the file if not exist. If exists, recreate again.

        private File createFile(String path, String fileName) throws IOException {
           ClassLoader classLoader = getClass().getClassLoader();
           File file = new File(classLoader.getResource(".").getFile() + path + fileName);
    
           // Lets create the directory
           try {
              file.getParentFile().mkdir();
           } catch (Exception err){
               System.out.println("ERROR (Directory Create)" + err.getMessage());
           }
    
           // Lets create the file if we have credential
           try {
               file.createNewFile();
           } catch (Exception err){
               System.out.println("ERROR (File Create)" + err.getMessage());
           }
           return  file;
       }
    
    0 讨论(0)
  • 2020-12-12 15:08

    code:

    // Create Directory if not exist then Copy a file.
    
    
    public static void copyFile_Directory(String origin, String destDir, String destination) throws IOException {
    
        Path FROM = Paths.get(origin);
        Path TO = Paths.get(destination);
        File directory = new File(String.valueOf(destDir));
    
        if (!directory.exists()) {
            directory.mkdir();
        }
            //overwrite the destination file if it exists, and copy
            // the file attributes, including the rwx permissions
         CopyOption[] options = new CopyOption[]{
                    StandardCopyOption.REPLACE_EXISTING,
                    StandardCopyOption.COPY_ATTRIBUTES
    
            };
            Files.copy(FROM, TO, options);
    
    
    }
    
    0 讨论(0)
  • 2020-12-12 15:15

    Using java.nio.Path it would be quite simple -

    public static Path createFileWithDir(String directory, String filename) {
            File dir = new File(directory);
            if (!dir.exists()) dir.mkdirs();
            return Paths.get(directory + File.separatorChar + filename);
        }
    
    0 讨论(0)
  • 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();
    }
    
    0 讨论(0)
  • 2020-12-12 15:23

    java 8+ version

    Files.createDirectories(Paths.get("/Your/Path/Here"));
    

    The Files.createDirectories

    creates a new directory and parent directories that do not exist.

    The method does not thrown an exception if the directory already exist.

    0 讨论(0)
  • 2020-12-12 15:23

    Trying to make this as short and simple as possible. Creates directory if it doesn't exist, and then returns the desired file:

    /** Creates parent directories if necessary. Then returns file */
    private static File fileWithDirectoryAssurance(String directory, String filename) {
        File dir = new File(directory);
        if (!dir.exists()) dir.mkdirs();
        return new File(directory + "/" + filename);
    }
    
    0 讨论(0)
提交回复
热议问题