copy Folder - Android File Input Output

Android examples for File Input Output:Copy File

Description

copy Folder

Demo Code


//package com.java2s;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Main {
    private static void copyFolder(File fromFolder, File toFolder)
            throws IOException {
        if (!fromFolder.exists()) {
            return;
        }//w  w  w  .  j av  a 2s  . c  o m
        if (toFolder.exists()) {
            deleteFileAndFolder(toFolder);
        }
        copyFolder(fromFolder.getAbsolutePath(), toFolder.getAbsolutePath());
    }

    public static void copyFolder(String sourceDir, String targetDir)
            throws IOException {
        // ??????
        (new File(targetDir)).mkdirs();
        // ???????????????????
        File[] file = (new File(sourceDir)).listFiles();
        for (int i = 0; i < file.length; i++) {
            if (file[i].isFile()) {
                // ????
                File sourceFile = file[i];
                // ????
                File targetFile = new File(
                        new File(targetDir).getAbsolutePath()
                                + File.separator + file[i].getName());
                copyFile(sourceFile, targetFile);
            }
            if (file[i].isDirectory()) {
                // ???????????
                String dir1 = sourceDir + "/" + file[i].getName();
                // ???????????
                String dir2 = targetDir + "/" + file[i].getName();
                copyFolder(dir1, dir2);
            }
        }
    }

    private static void deleteFileAndFolder(File fileOrFolder) {
        if (fileOrFolder == null || !fileOrFolder.exists()) {
            return;
        }
        if (fileOrFolder.isDirectory()) {
            File[] children = fileOrFolder.listFiles();
            if (children != null) {
                for (File childFile : children) {
                    deleteFileAndFolder(childFile);
                }
            }
        } else {
            fileOrFolder.delete();
        }
    }

    private static void copyFile(File from, File to) {
        if (!from.exists()) {
            return;
        }
        FileInputStream in = null;
        FileOutputStream out = null;
        try {
            in = new FileInputStream(from);
            out = new FileOutputStream(to);

            byte bt[] = new byte[1024];
            int c;
            while ((c = in.read(bt)) > 0) {
                out.write(bt, 0, c);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}

Related Tutorials