Java File Copy nio copy(File srcDir, File relSrcFile, File destDir, File relDestFile)

Here you can find the source of copy(File srcDir, File relSrcFile, File destDir, File relDestFile)

Description

Copy the specified source file given relative to the specified source folder to the specified destination file relative to the specified destination folder

License

Apache License

Declaration

public static void copy(File srcDir, File relSrcFile, File destDir, File relDestFile) throws IOException 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.File;
import java.io.IOException;

import java.nio.file.Files;

import java.nio.file.StandardCopyOption;

public class Main {
    /**/*from  w ww.ja va  2 s .  c om*/
     * Copy the specified source file given relative to the specified source folder
     * to the specified destination file relative to the specified destination folder
     */
    public static void copy(File srcDir, File relSrcFile, File destDir, File relDestFile) throws IOException {
        File finalSrcFile = (srcDir != null) ? new File(srcDir, relSrcFile.getPath()) : relSrcFile;
        File relDestDir = relDestFile.getParentFile();
        if (relDestDir != null) {
            File finalDestDir = (destDir != null) ? new File(destDir, relDestDir.getPath()) : relDestDir;
            mkdirs(finalDestDir);
        }
        File finalDestFile = new File(destDir, relDestFile.getPath());
        Files.copy(finalSrcFile.toPath(), finalDestFile.toPath(), StandardCopyOption.REPLACE_EXISTING,
                StandardCopyOption.COPY_ATTRIBUTES);
    }

    /**
     * Just a simple wrapper around `java.util.File.mkdirs()` that fails
     * when trying to create a folder named "~"
     */
    public static boolean mkdirs(File dir) {
        String path = dir.getPath().replace('\\', '/');
        if (path.equals("~") || path.startsWith("~/") || path.contains("/~/")) {
            return false;
        }
        return dir.mkdirs();
    }
}

Related

  1. copy(File src, File dst)
  2. copy(File src, File dst)
  3. copy(File src, File folder)
  4. copy(File src, File target)
  5. copy(File src, File target)
  6. copy(File srcfile, File destfile)
  7. copy(File srcFile, File dstFile)
  8. copy(File srcFileOrDir, File targetFileOrDir)
  9. copy(File toFile, File fromFile)