【Android】简单实现拷贝文件和文件夹到另一个目录下

本文提供了一种复制文件和文件夹的方法,包括单个文件的复制及整个文件夹内所有文件的递归复制。代码实现了从源路径到目标路径的文件内容复制,并检查了文件的存在性和可读性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转载请注明出处,原文链接:https://blog.csdn.net/u013642500/article/details/80067680


本方法使用前提是已拥有权限,未对权限不足情况进行处理,如有需要可自行添加。

关于读写权限的总结请参考:https://blog.csdn.net/u010784887/article/details/53560025

    /**
     * 复制单个文件
     *
     * @param oldPath$Name String 原文件路径+文件名 如:data/user/0/com.test/files/abc.txt
     * @param newPath$Name String 复制后路径+文件名 如:data/user/0/com.test/cache/abc.txt
     * @return <code>true</code> if and only if the file was copied;
     *         <code>false</code> otherwise
     */
    public boolean copyFile(String oldPath$Name, String newPath$Name) {
        try {
            File oldFile = new File(oldPath$Name);
            if (!oldFile.exists()) {
                Log.e("--Method--", "copyFile:  oldFile not exist.");
                return false;
            } else if (!oldFile.isFile()) {
                Log.e("--Method--", "copyFile:  oldFile not file.");
                return false;
            } else if (!oldFile.canRead()) {
                Log.e("--Method--", "copyFile:  oldFile cannot read.");
                return false;
            }

            /* 如果不需要打log,可以使用下面的语句
            if (!oldFile.exists() || !oldFile.isFile() || !oldFile.canRead()) {
                return false;
            }
            */

            FileInputStream fileInputStream = new FileInputStream(oldPath$Name);
            FileOutputStream fileOutputStream = new FileOutputStream(newPath$Name);
            byte[] buffer = new byte[1024];
            int byteRead;
            while (-1 != (byteRead = fileInputStream.read(buffer))) {
                fileOutputStream.write(buffer, 0, byteRead);
            }
            fileInputStream.close();
            fileOutputStream.flush();
            fileOutputStream.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 复制文件夹及其中的文件
     *
     * @param oldPath String 原文件夹路径 如:data/user/0/com.test/files
     * @param newPath String 复制后的路径 如:data/user/0/com.test/cache
     * @return <code>true</code> if and only if the directory and files were copied;
     *         <code>false</code> otherwise
     */
    public boolean copyFolder(String oldPath, String newPath) {
        try {
            File newFile = new File(newPath);
            if (!newFile.exists()) {
                if (!newFile.mkdirs()) {
                    Log.e("--Method--", "copyFolder: cannot create directory.");
                    return false;
                }
            }
            File oldFile = new File(oldPath);
            String[] files = oldFile.list();
            File temp;
            for (String file : files) {
                if (oldPath.endsWith(File.separator)) {
                    temp = new File(oldPath + file);
                } else {
                    temp = new File(oldPath + File.separator + file);
                }

                if (temp.isDirectory()) {   //如果是子文件夹
                    copyFolder(oldPath + "/" + file, newPath + "/" + file);
                } else if (!temp.exists()) {
                    Log.e("--Method--", "copyFolder:  oldFile not exist.");
                    return false;
                } else if (!temp.isFile()) {
                    Log.e("--Method--", "copyFolder:  oldFile not file.");
                    return false;
                } else if (!temp.canRead()) {
                    Log.e("--Method--", "copyFolder:  oldFile cannot read.");
                    return false;
                } else {
                    FileInputStream fileInputStream = new FileInputStream(temp);
                    FileOutputStream fileOutputStream = new FileOutputStream(newPath + "/" + temp.getName());
                    byte[] buffer = new byte[1024];
                    int byteRead;
                    while ((byteRead = fileInputStream.read(buffer)) != -1) {
                        fileOutputStream.write(buffer, 0, byteRead);
                    }
                    fileInputStream.close();
                    fileOutputStream.flush();
                    fileOutputStream.close();
                }

                /* 如果不需要打log,可以使用下面的语句
                if (temp.isDirectory()) {   //如果是子文件夹
                    copyFolder(oldPath + "/" + file, newPath + "/" + file);
                } else if (temp.exists() && temp.isFile() && temp.canRead()) {
                    FileInputStream fileInputStream = new FileInputStream(temp);
                    FileOutputStream fileOutputStream = new FileOutputStream(newPath + "/" + temp.getName());
                    byte[] buffer = new byte[1024];
                    int byteRead;
                    while ((byteRead = fileInputStream.read(buffer)) != -1) {
                        fileOutputStream.write(buffer, 0, byteRead);
                    }
                    fileInputStream.close();
                    fileOutputStream.flush();
                    fileOutputStream.close();
                }
                 */
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

/**
 * 复制单个文件
 *
 * @param oldPath$Name String 原文件路径+文件名 如:data/user/0/com.test/files/abc.txt
 * @param newPath$Name String 复制后路径+文件名 如:data/user/0/com.test/cache/abc.txt
 * @return <code>true</code> if and only if the file was copied;
 * <code>false</code> otherwise
 */
public boolean copyFile(String oldPath$Name, String newPath$Name) {
    try {
        File oldFile = new File(oldPath$Name);
        if (!oldFile.exists()) {
            Log.e("--Method--", "copyFile:  oldFile not exist.");
            return false;
        } else if (!oldFile.isFile()) {
            Log.e("--Method--", "copyFile:  oldFile not file.");
            return false;
        } else if (!oldFile.canRead()) {
            Log.e("--Method--", "copyFile:  oldFile cannot read.");
            return false;
        }

        /* 如果不需要打log,可以使用下面的语句
        if (!oldFile.exists() || !oldFile.isFile() || !oldFile.canRead()) {
            return false;
        }
        */

        FileInputStream fileInputStream = new FileInputStream(oldPath$Name);    //读入原文件
         FileOutputStream fileOutputStream = new FileOutputStream(newPath$Name);
        byte[] buffer = new byte[1024];
        int byteRead;
        while ((byteRead = fileInputStream.read(buffer)) != -1) {
            fileOutputStream.write(buffer, 0, byteRead);
        }
        fileInputStream.close();
        fileOutputStream.flush();
        fileOutputStream.close();
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

/**
 * 复制文件夹及其中的文件
 *
 * @param oldPath String 原文件夹路径 如:data/user/0/com.test/files
 * @param newPath String 复制后的路径 如:data/user/0/com.test/cache
 * @return <code>true</code> if and only if the directory and files were copied;
 * <code>false</code> otherwise
 */
public boolean copyFolder(String oldPath, String newPath) {
    try {
        File newFile = new File(newPath);
        if (!newFile.exists()) {
            if (!newFile.mkdirs()) {
                Log.e("--Method--", "copyFolder: cannot create directory.");
                return false;
            }
        }
        File oldFile = new File(oldPath);
        String[] files = oldFile.list();
        File temp;
        for (String file : files) {
            if (oldPath.endsWith(File.separator)) {
                temp = new File(oldPath + file);
            } else {
                temp = new File(oldPath + File.separator + file);
            }

            if (temp.isDirectory()) {   //如果是子文件夹
                copyFolder(oldPath + "/" + file, newPath + "/" + file);
            } else if (!temp.exists()) {
                Log.e("--Method--", "copyFolder:  oldFile not exist.");
                return false;
            } else if (!temp.isFile()) {
                Log.e("--Method--", "copyFolder:  oldFile not file.");
                return false;
            } else if (!temp.canRead()) {
                Log.e("--Method--", "copyFolder:  oldFile cannot read.");
                return false;
            } else {
                FileInputStream fileInputStream = new FileInputStream(temp);
                FileOutputStream fileOutputStream = new FileOutputStream(newPath + "/" + temp.getName());
                byte[] buffer = new byte[1024];
                int byteRead;
                while ((byteRead = fileInputStream.read(buffer)) != -1) {
                    fileOutputStream.write(buffer, 0, byteRead);
                }
                fileInputStream.close();
                fileOutputStream.flush();
                fileOutputStream.close();
            }

            /* 如果不需要打log,可以使用下面的语句
            if (temp.isDirectory()) {   //如果是子文件夹
                copyFolder(oldPath + "/" + file, newPath + "/" + file);
            } else if (temp.exists() && temp.isFile() && temp.canRead()) {
                FileInputStream fileInputStream = new FileInputStream(temp);
                FileOutputStream fileOutputStream = new FileOutputStream(newPath + "/" + temp.getName());
                byte[] buffer = new byte[1024];
                int byteRead;
                while ((byteRead = fileInputStream.read(buffer)) != -1) {
                    fileOutputStream.write(buffer, 0, byteRead);
                }
                fileInputStream.close();
                fileOutputStream.flush();
                fileOutputStream.close();
            }
            */
        }
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}


缺陷:复制单文件时(copyFile),无法判断新文件夹是否存在、新文件是否能否写入。

由于本人安卓知识及技术有限,代码如有错误或不足请评论指出,非常感谢!

感谢伊茨米可的原创博客,本文参考链接:https://blog.csdn.net/etzmico/article/details/7786525/

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` 类可以用于递归地复制整个目录结构并清理不需要的文件。 记得处理可能出现的权限问题,因为访问某些文件目录可能需要用户的特殊权限。此外,谨慎使用,因为大量文件的复制可能会消耗大量的系统资源。
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值