将文件从SD卡的文件夹复制到SD卡的另一个文件夹

问题描述 投票:20回答:5

是否可以以编程方式将sdcard中存在的文件夹复制到存在相同sdcard的另一个文件夹中?

如果是,该怎么做?

android copy directory android-sdcard android-file
5个回答
41
投票

该示例的改进版本:

// If targetLocation does not exist, it will be created.
public void copyDirectory(File sourceLocation , File targetLocation)
throws IOException {

    if (sourceLocation.isDirectory()) {
        if (!targetLocation.exists() && !targetLocation.mkdirs()) {
            throw new IOException("Cannot create dir " + targetLocation.getAbsolutePath());
        }

        String[] children = sourceLocation.list();
        for (int i=0; i<children.length; i++) {
            copyDirectory(new File(sourceLocation, children[i]),
                    new File(targetLocation, children[i]));
        }
    } else {

        // make sure the directory we plan to store the recording in exists
        File directory = targetLocation.getParentFile();
        if (directory != null && !directory.exists() && !directory.mkdirs()) {
            throw new IOException("Cannot create dir " + directory.getAbsolutePath());
        }

        InputStream in = new FileInputStream(sourceLocation);
        OutputStream out = new FileOutputStream(targetLocation);

        // Copy the bits from instream to outstream
        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        in.close();
        out.close();
    }
}

如果传递的目标文件位于不存在的目录中,则可以提供更好的错误处理和更好的处理。


14
投票

请参见示例here。 sdcard是外部存储,因此您可以通过getExternalStorageDirectory访问它。


4
投票

是,在我的代码中,我可以使用下面的方法。希望对您有用:-

getExternalStorageDirectory

1
投票

要移动文件或目录,可以使用public static void copyDirectoryOneLocationToAnotherLocation(File sourceLocation, File targetLocation) throws IOException { if (sourceLocation.isDirectory()) { if (!targetLocation.exists()) { targetLocation.mkdir(); } String[] children = sourceLocation.list(); for (int i = 0; i < sourceLocation.listFiles().length; i++) { copyDirectoryOneLocationToAnotherLocation(new File(sourceLocation, children[i]), new File(targetLocation, children[i])); } } else { InputStream in = new FileInputStream(sourceLocation); OutputStream out = new FileOutputStream(targetLocation); // Copy the bits from instream to outstream byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.close(); } } 功能

File.renameTo(String path)

0
投票

科特林码

File oldFile = new File (oldFilePath);
oldFile.renameTo(newFilePath);
© www.soinside.com 2019 - 2024. All rights reserved.