集册 Java实例教程 复制文件树

复制文件树

欢马劈雪     最近更新时间:2020-01-02 10:19:05

533
复制文件树


import static javax.swing.JOptionPane.ERROR_MESSAGE;/** NowJava.com 提 供 **/

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 {
        /*
        N o w J a v a . c o 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);
展开阅读全文