Copy copy file sourceFile to the directory destination directory - Android java.io

Android examples for java.io:Directory

Description

Copy copy file sourceFile to the directory destination directory

Demo Code

import android.util.Log;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Main{

    private static final String TAG = FileSystemUtils.class.getSimpleName();
    /**//from w  w  w . j  av  a  2s  .c  o m
     * Copy copy file sourceFile to the directory destination directory
     * @param destinationDirectory location where the file to be copied
     * @param sourceFile the location of the file to copy
     * @param targetFileName name of the target file
     * @return true if the file was copied successfully, false otherwise
     */
    public static boolean copyFile(final File destinationDirectory,
            final File sourceFile, final String targetFileName) {
        boolean _return = false;

        if (null != destinationDirectory && null != sourceFile) {
            FileInputStream inputStream = null;
            FileOutputStream outputStream = null;
            byte[] dataBuffer = new byte[1024];
            File outputFile = new File(
                    destinationDirectory.getAbsoluteFile() + File.separator
                            + targetFileName);
            try {
                inputStream = new FileInputStream(sourceFile);
                outputStream = new FileOutputStream(outputFile);

                try {
                    int bytesRead = inputStream.read(dataBuffer);
                    while (-1 != bytesRead) {
                        outputStream.write(dataBuffer, 0, bytesRead);
                        bytesRead = inputStream.read(dataBuffer);
                    }

                    // No errors copying the file, look like we're good
                    _return = true;
                } catch (IOException e) {
                    Log.w(TAG, "IOException trying to write copy file ["
                            + sourceFile.getAbsolutePath() + "] to ["
                            + destinationDirectory.getAbsolutePath()
                            + "]: [" + e.getMessage() + "]");
                }
            } catch (FileNotFoundException e) {
                Log.w(TAG,
                        "File not found exception trying to write copy file ["
                                + sourceFile.getAbsolutePath() + "] to ["
                                + destinationDirectory.getAbsolutePath()
                                + "]: [" + e.getMessage() + "]");
            }
        }
        return _return;
    }

}

Related Tutorials