copy File Tree - Java File Path IO

Java examples for File Path IO:Directory Copy

Description

copy File Tree

Demo Code


import static javax.swing.JOptionPane.ERROR_MESSAGE;
import static javax.swing.JOptionPane.NO_OPTION;
import static javax.swing.JOptionPane.QUESTION_MESSAGE;
import static javax.swing.JOptionPane.YES_NO_OPTION;
import static javax.swing.JOptionPane.showConfirmDialog;
import static javax.swing.JOptionPane.showMessageDialog;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;

public class Main{
    public static String copyTree(File srcFile, File dstFolder) {
        try {/*from  w ww  .j a va2s .  co  m*/
            String fname = srcFile.getName();
            File copyTo = new File(dstFolder, fname);
            if (copyTo.exists()) {
                if (copyTo.isFile()) {
                    if (showConfirmDialog(null,
                            "Do you want to override file " + copyTo + "?",
                            "Copy", YES_NO_OPTION, QUESTION_MESSAGE) == NO_OPTION) {
                        return "";
                    }
                    Files.copy(srcFile.toPath(), copyTo.toPath(),
                            StandardCopyOption.REPLACE_EXISTING);
                } else {
                    return String.format(
                            "<html>Cannot copy <b>%s</b> to <b>%s</b>.",
                            projectRelative(srcFile.toPath()),
                            projectRelative(dstFolder.toPath()));
                }
            } else {
                if (srcFile.isDirectory()) {
                    copyTo.mkdir();
                    for (File file : srcFile.listFiles()) {
                        copyTree(file, copyTo);
                    }
                } else {
                    Files.copy(srcFile.toPath(), copyTo.toPath(),
                            StandardCopyOption.REPLACE_EXISTING);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            showMessageDialog(null, e, "Copy", ERROR_MESSAGE);
        }
        return null;
    }
    public static Path projectRelative(Path path) {
        return Project.getInstance().getProjectFolder().getFilePath()
                .relativize(path);
    }
}

Related Tutorials