与所有孩子一起复制目录

时间:2015-04-16 20:12:39

标签: android

根据this link在Android Studio中构建一个java模块,下面的代码没有编译,我试图创建一个新的FileUtil对象,以便在其上调用copyDirectory函数无效。

public class MyClass {
public static void main(String[] args) throws IOException {
    String old_name = "Six";
    String new_name = "Seven";

    String old_file_name = "C:\\Users\\Jack\\AndroidStudioProjects\\" + old_name;
    String new_file_name = "C:\\Users\\Jack\\AndroidStudioProjects\\" + new_name;

    File srcDir = new File(old_file_name);
    File destDir = new File(new_file_name);

    copyDirectory(srcDir, destDir);
}

}

1 个答案:

答案 0 :(得分:1)

您可能需要这些功能

public static void copyFileOrDirectory(String srcDir, String dstDir) {

    try {
        File src = new File(srcDir);
        File dst = new File(dstDir, src.getName());

        if (src.isDirectory()) {

            String files[] = src.list();
            int filesLength = files.length;
            for (int i = 0; i < filesLength; i++) {
                String src1 = (new File(src, files[i]).getPath());
                String dst1 = dst.getPath();
                copyFileOrDirectory(src1, dst1);

            }
        } else {
            copyFile(src, dst);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public static void copyFile(File sourceFile, File destFile) throws IOException {
    if (!destFile.getParentFile().exists())
        destFile.getParentFile().mkdirs();

    if (!destFile.exists()) {
        destFile.createNewFile();
    }

    FileChannel source = null;
    FileChannel destination = null;

    try {
        source = new FileInputStream(sourceFile).getChannel();
        destination = new FileOutputStream(destFile).getChannel();
        destination.transferFrom(source, 0, source.size());
    } finally {
        if (source != null) {
            source.close();
        }
        if (destination != null) {
            destination.close();
        }
    }
}