Gastón Saillén
Gastón Saillén

Reputation: 13129

How to delete a file from internal memory before replacing it

I would like to delete an internal file at runtime. When I download from an external server, the old version of the file (with the same name) is replaced, however I am unable to read it. I think that I need to delete the previous file before downloading the new version. Here is an example of what I have tried so far:

try {
    FileOutputStream fos = getApplicationContext().openFileOutput("mytext.txt", Context.MODE_PRIVATE);
    fos.write(getStringFromFile(pictosFile.getAbsolutePath()).getBytes());
    Log.e("mytextfile",""+getStringFromFile(pictosFile.getAbsolutePath()));
    progressDialog.cancel();
    fos.close();
} 
catch (IOException e) {
    e.printStackTrace();
} 
catch (Exception e) {
    e.printStackTrace();
}

This allows me to save the file into internal memory, but I am unsure about how to delete the previous file before writing the new version.

Upvotes: 3

Views: 59

Answers (1)

sparkitny
sparkitny

Reputation: 1533

If you need to ensure that the file is overwritten, i.e. delete an old copy before saving a new version, you can use the exists() method for a file object. Here is an example showing how to delete an old version of an image file before writing a new file with the same name in a nested directory:

// Here TARGET_BASE_PATH is the path to the base folder
// where the file is to be stored

// 1 - Check that the file exists and delete if it does
File myDir = new File(TARGET_BASE_PATH);
// Create the nested directory structure if it does not exist (first write)
if(!myDir.exists())
    myDir.mkdirs();
String fname = "my_new_image.jpg";
File file = new File(myDir,fname);
// Delete the previous versions of the file if it exists
if(file.exists())
    file.delete();
String filename = file.toString();
BufferedOutputStream bos = null;

// 2 - Write the new version of the file to the same location
try{
    bos = new BufferedOutputStream(new FileOutputStream(filename));
    Bitmap bmp = Bitmap.createBitmap(width,height,Bitmap.Config.ARGB_8888);
    bmp.copyPixelsFromBuffer(buf);
    bmp.compress(Bitmap.CompressFormat.PNG,90,bos);
    bmp.recycle();
}
catch(FileNotFoundException e){
    e.printStackTrace();
}
finally{
    try{
        if(bos != null)
            bos.close();
    }
    catch(IOException e){
        e.printStackTrace();
    }
}

You must also ensure that you have read / write access to memory, make sure that you ask the user for these permissions at run time and have the following in your manifest:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

Upvotes: 3

Related Questions