How to programmatically transfer files from internal memory to sdcard in android?

How to transfer files from the device’s internal memory to the external memory in Android? Please provide code examples. My code is below

    private void moveFile(File file, File dir) throws IOException {
    File newFile = new File(dir, file.getName());
    FileChannel outputChannel = null;
    FileChannel inputChannel = null;
    try {
        outputChannel = new FileOutputStream(newFile).getChannel();
        inputChannel = new FileInputStream(file).getChannel();
        inputChannel.transferTo(0, inputChannel.size(), outputChannel);
        inputChannel.close();
        file.delete();
    } finally {
        if (inputChannel != null) inputChannel.close();
        if (outputChannel != null) outputChannel.close();
    }

}
+4
source share
1 answer

Remove the trailing slash from your path. This is not necessary since example.png is not a directory. In fact, do not reinstall the path to the SD card, as it may differ from device to device. Try Environment.getExternalStorageDirectory () to get the sdcard path, then add any final path to the end.

Please see the documentation .

+1
source

All Articles