move File Tree - Java File Path IO

Java examples for File Path IO:Directory Copy

Description

move 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 moveTree(File srcFile, File dstFolder) {
        try {/*from w ww . j  ava 2  s  . co  m*/
            String fname = srcFile.getName();
            File moveTo = new File(dstFolder, fname);
            if (moveTo.exists()) {
                if (moveTo.isFile()) {
                    if (showConfirmDialog(null,
                            "Do you want to override file " + moveTo + "?",
                            "Move", YES_NO_OPTION, QUESTION_MESSAGE) == NO_OPTION) {
                        return "";
                    }
                    Files.move(srcFile.toPath(), moveTo.toPath(),
                            StandardCopyOption.REPLACE_EXISTING);
                } else {
                    return String.format(
                            "<html>Cannot move <b>%s</b> to <b>%s</b>.",
                            projectRelative(srcFile.toPath()),
                            projectRelative(dstFolder.toPath()));
                }
            } else {
                Files.move(srcFile.toPath(), moveTo.toPath(),
                        StandardCopyOption.REPLACE_EXISTING);
            }
        } catch (IOException e) {
            e.printStackTrace();
            showMessageDialog(null, e, "Move", ERROR_MESSAGE);
        }
        return null;
    }
    public static Path projectRelative(Path path) {
        return Project.getInstance().getProjectFolder().getFilePath()
                .relativize(path);
    }
}

Related Tutorials