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

2023-12-31

有一个image file里面一个directory。如何copy this image file进入另一个directory那是刚刚创建的?他们俩directories都在同一个internal storage设备的:)


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

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

<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();
            }
        }
    }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何以编程方式将文件复制到另一个目录? 的相关文章

随机推荐