Ammar Samater
Ammar Samater

Reputation: 539

about saving file to external storage in android

I have a question about this code I found on Android saving file to external storage

Before rushing to down vote, I'm asking this here because I'm not allowed to comment on answered questions.

    private void saveImageToExternalStorage(Bitmap finalBitmap) {
    String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
    File myDir = new File(root + "/saved_images");
    myDir.mkdirs();
    Random generator = new Random();
    int n = 10000;
    n = generator.nextInt(n);
    String fname = "Image-" + n + ".jpg";
    //////////////////////////////////////////////////////////////////////////////////

    File file = new File(myDir, fname);    
    if (file.exists())                        // why check if it exists and delete file??????????                       
        file.delete();

    try {
       FileOutputStream out = new FileOutputStream(file);             // how is it being used if it is deleted???
       finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
       out.flush();
       out.close();
     }
         catch (Exception e) {
         e.printStackTrace();
    }


    // Tell the media scanner about the new file so that it is
    // immediately available to the user.
   MediaScannerConnection.scanFile(this, new String[] { file.toString() }, null,
            new MediaScannerConnection.OnScanCompletedListener() {
                public void onScanCompleted(String path, Uri uri) {
                    Log.i("ExternalStorage", "Scanned " + path + ":");
                    Log.i("ExternalStorage", "-> uri=" + uri);
                }
    });

}

my question is about the

if (file.exists())       

isn't this always executed after the statement above is executed? also why delete it after creating it, Does the statement only delete the contents and not the actual file. I read the Java doc's but it didn't clarify this for me.

thank you.

Upvotes: 1

Views: 79

Answers (1)

CommonsWare
CommonsWare

Reputation: 1007584

isn't this always executed after the statement above is executed?

Well, yes.

also why delete it after creating it

new File(...) does not create a file on disk. It creates a File object in the Java programming language.

Does the statement only delete the contents and not the actual file

delete() deletes the file.

I read the Java doc's but it didn't clarify this for me.

Quoting the documentation: "The actual file referenced by a File may or may not exist. It may also, despite the name File, be a directory or other non-regular file."

Upvotes: 3

Related Questions