Pisike007
Pisike007

Reputation: 101

creating a copy of sdcard picture to another directory?

i am able to get the path of the picture i want to copy, and able to get the path from where i want it to be copy, but still cant find the way to copy them. any suggestion?

private void copyPictureToFolder(String picturePath, String folderName)
            throws IOException {
        Log.d("debug", folderName);
        Log.d("debug", picturePath);

        try {
            FileInputStream fileInputStream = new FileInputStream(picturePath);
            FileOutputStream fileOutputStream = new FileOutputStream(folderName+"/");

            int bufferSize;
            byte[] bufffer = new byte[512];
            while ((bufferSize = fileInputStream.read(bufffer)) > 0) {
                fileOutputStream.write(bufffer, 0, bufferSize);
            }
            fileInputStream.close();
            fileOutputStream.close();
        } catch (Exception e) {
            Log.d("disaster","didnt work");
        }

    }

thanks.

Upvotes: 2

Views: 49

Answers (1)

Snicolas
Snicolas

Reputation: 38168

You should use Commons-IO to copy a file, we are in 2013 ! No one wants do that manually. If you really want then you should consider a few things :

  • first a loop that copies your file, at every iteration you copy buffer.length bytes. In you current code, you don't loop and copy 512 bytes of source image into dest (whatever the source image size is).
  • take care of last iteration and only copy what you read
  • your try/catch structure is not correct, you should add a finally close to always close your source and destination file. Look here for an example : what is the exact order of execution for try, catch and finally?

With IOUtils, it will give something like

try {
  IOUtils.copy( source, dest );
} finally {
  IOUtils.closeQuietly( source );
  IOUtils.closeQuietly( dest );
}

and don't catch anything, it will be forwarded to the caller.

Upvotes: 1

Related Questions