android - 如何以编程方式将文件复制到另一个目录?

标签 android

目录 中有一个图像文件。如何将这个图像文件复制到刚刚创建的另一个目录中?这两个目录在设备的同一个内部存储上:)

最佳答案

您可以使用这些功能。如果您传入文件,第一个将复制包含所有子项或单个文件的整个目录。第二个仅对文件有用,并为第一个中的每个文件调用。

另请注意,您需要具有执行此操作的权限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />  

函数:

 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();
            }
        }
    }

关于android - 如何以编程方式将文件复制到另一个目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29867121/

相关文章:

jquery mobile - 在 android 上太宽了

android - Jersey 客户端需要 Android 中缺少的 XMLInputFactory

java - 检查 AlarmManager 任务是否正在进行

android - 从 XML 加载 fragment 时动画 fragment 转换

android - 如何使用导航组件保持对话框打开?

javascript - 如何用jQuery或js实现3D曲线墙

Android如何加密/解密数据库

android - 加密文本出现错误

java - 如何使用Android获取xml中的根元素?

java - Firebase Auth 在单击按钮时未启动 Activity 但在关闭并重新打开应用程序时有效