将文件从内部存储移动到SD卡

时间:2019-09-09 08:32:48

标签: android sd-card movefile

我想将文件从内部存储移动到SD卡。我尝试使用Environment.getExternalStorageDirectory(),但它仅移动内部存储。

我使用了以下代码:

ContextCompat.getExternalFilesDirs(mActivity, null)[0]

但是它在包文件夹中移动

/storage/emulated/0/Android/data/com.unzipdemo/files/MyFileStorage/SampleFile.txt

我想在特定的文件夹名称中移动文件。您能帮我解决吗?

1 个答案:

答案 0 :(得分:0)

尝试使用此方法copyDirectoryOneLocationToAnotherLocation()

  

将内部文件值作为源位置和外部文件路径传递   作为目标位置

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

    }

注意:-复制后,删除源文件