Android拷贝文件夹和文件方法

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;


public class FileUtils {

    private static LogUtil log = LogUtil.get(FileUtils.class.getSimpleName());

    /**
     * 拷贝文件夹
     *
     * @param srcDir  源文件夹
     * @param destDir 目标文件夹
     * @throws IOException 读写异常
     */
    public static void copyDirectory(File srcDir, File destDir) {
        if (srcDir == null || destDir == null) {
            return;
        }
        log.i("copyDirectory start srcDir=" + srcDir.getAbsolutePath() + "   destDir=" + destDir.getAbsolutePath());
        if (!srcDir.exists()) {
            log.i("copyDirectory IllegalArgumentException=Source directory does not exist.");
        }
        if (!destDir.exists() && !destDir.mkdir()) {
            log.i("copyDirectory IllegalArgumentException=Destination directory cannot be created.");
            createSeparator(destDir.getAbsolutePath());
        }
        if (!srcDir.isDirectory()) {
            log.i("copyDirectory IllegalArgumentException=Source is not a directory.");
        }
        deleteDirectory(destDir);
        //遍历源文件夹数据
        File[] files = srcDir.listFiles();
        if (files != null && files.length != 0) {
            for (File file : files) {
                if (file.isDirectory()) {
                    // 如果是文件夹重复调用
                    copyDirectory(file, new File(destDir, file.getName()));
                } else {
                    // 是文件执行拷贝操作
                    FileInputStream inStream = null;
                    FileOutputStream outStream = null;
                    try {
                        log.e("copyDirectory file =" + file.getAbsolutePath());
                        inStream = new FileInputStream(file);
                        outStream = new FileOutputStream(new File(destDir, file.getName()));
                        byte[] buffer = new byte[1024];
                        int length;
                        while ((length = inStream.read(buffer)) > 0) {
                            outStream.write(buffer, 0, length);
                        }
                        log.e("copyDirectory end");
                    } catch (Exception e) {
                        log.e("copyDirectory e=" + e.getMessage());
                    } finally {
                        if (inStream != null) {
                            try {
                                inStream.close();
                            } catch (IOException e) {
                                log.e("copyDirectory IOException1=" + e.getMessage());
                            }
                        }
                        if (outStream != null) {
                            try {
                                outStream.close();
                            } catch (IOException e) {
                                log.e("copyDirectory IOException2=" + e.getMessage());
                            }
                        }
                    }

                }
            }
            log.d("copyDirectory end");
        } else {
            log.d("copyDirectory files is null srcDir=" + srcDir.getAbsolutePath());
        }
    }


    /**
     * 拷贝文件
     *
     * @param srcFile  源文件
     * @param destFile 目标文件
     * @throws IOException 读写异常
     */
    public static void copyFile(File srcFile, File destFile) {
        if (srcFile == null || destFile == null) {
            return;
        }
        log.i("copyFile start srcFile=" + srcFile.getAbsolutePath() + "   destFile=" + destFile.getAbsolutePath());
        // 是文件执行拷贝操作
        FileInputStream inStream = null;
        FileOutputStream outStream = null;
        try {
            inStream = new FileInputStream(srcFile);
            outStream = new FileOutputStream(destFile);
            byte[] buffer = new byte[1024];
            int length;
            while ((length = inStream.read(buffer)) > 0) {
                outStream.write(buffer, 0, length);
            }
            log.e("copyFile end");
        } catch (Exception e) {
            log.e("copyFile e=" + e.getMessage());
        } finally {
            if (inStream != null) {
                try {
                    inStream.close();
                } catch (IOException e) {
                    log.e("copyFile IOException1=" + e.getMessage());
                }
            }
            if (outStream != null) {
                try {
                    outStream.close();
                } catch (IOException e) {
                    log.e("copyFile IOException2=" + e.getMessage());
                }
            }
        }

    }


    /**
     * 读取文件内容 txt等
     */
    public static void readContent(String filePath) {
        BufferedReader buffReader = null;
        InputStream inStream = null;
        InputStreamReader inputReader = null;
        StringBuilder content = new StringBuilder();
        try {
            inStream = new FileInputStream(filePath);
            if (inStream != null) {
                inputReader = new InputStreamReader(inStream, "UTF-8");
                buffReader = new BufferedReader(inputReader);
                String line = buffReader.readLine();
                //分行读取
                while (line != null) {
                    content.append(line + " ");
                    line = buffReader.readLine();
                }
                log.e("readContent content=" + content);
                inStream.close(); //关闭输入流
            }
        } catch (FileNotFoundException e) {
            log.e("readContent e1=" + e.getMessage());
        } catch (IOException e) {
            log.e("readContent e2=" + e.getMessage());
        } finally {

            try {
                if (inStream != null) {
                    inStream.close();
                    log.i("readContent---inStream close");
                }
            } catch (IOException e) {
                log.e("readContent---inStream close e=" + e.getMessage());
            }
            try {
                if (inputReader != null) {
                    inputReader.close();
                    log.i("inputReader---inStream close");
                }
            } catch (IOException e) {
                log.e("readContent---inputReader close e=" + e.getMessage());
            }

            try {
                if (buffReader != null) {
                    buffReader.close();
                    log.i("readContent---buffReader close");
                }
            } catch (IOException e) {
                log.e("readContent---buffReader close e=" + e.getMessage());
            }
        }
    }


    /**
     * 创建
     */
    public static String createSeparator(String path) {
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        if (path.endsWith("/")) {
            return path;
        }
        return path + '/';
    }

    /**
     * 删除文件夹内容
     */
    public static void deleteDirectory(File directory) {
        if (directory.exists()) {
            File[] files = directory.listFiles();
            if (null != files) {
                for (File file : files) {
                    if (file.isDirectory()) {
                        deleteDirectory(file);
                    } else {
                        file.delete();
                    }
                }
            }
        }
    }

}
Android应用中,遍历并复制文件夹通常是在后台任务或者服务中操作,例如用户需要同步数据或者初始化应用资源。你可以使用`java.io.File`类以及`java.nio.file.Files`类来实现这个功能。以下是一个简单的步骤: 1. 获取源文件夹路径:首先,获取你想复制的外部存储或内部存储的文件夹路径。 ```java File sourceFolder = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES) // 或者 Internal存储的相应路径 ``` 2. 创建目标文件夹(如果不存在):检查目标app目录是否存在,若不存在则创建。 ```java File targetFolder = new File(getApplicationCacheDirectory(), "copied_folder"); if (!targetFolder.exists()) { if (!targetFolder.mkdirs()) { Log.e("App", "Failed to create target folder"); } } ``` 3. 使用`Files.walk`遍历源文件夹,并复制每个文件。 ```java try (Stream<Path> stream = Files.walk(sourceFolder.toPath())) { stream.forEach(path -> { if (Files.isDirectory(path)) { copyDirectory(path, targetFolder); } else { copyFile(path, targetFolder); } }); } catch (IOException e) { Log.e("App", "Error while copying files", e); } private void copyDirectory(Path source, File target) throws IOException { Path targetPath = target.toPath(); Files.createDirectories(targetPath); List<SimpleFileVisitor<Path>> visitors = Arrays.asList( new CopyDirectoryVisitor(targetPath), new DeleteStartingWithVisitor(targetPath) ); Files.visitRecursively(source, visitors); } private void copyFile(Path source, File target) throws IOException { Files.copy(source, target.toPath()); } ``` 4. `CopyDirectoryVisitor` `DeleteStartingWithVisitor` 类可以用于递归地复制整个目录结构并清理不需要的文件。 记得处理可能出现的权限问题,因为访问某些文件或目录可能需要用户的特殊权限。此外,谨慎使用,因为大量文件的复制可能会消耗大量的系统资源。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值