如何在替换文件之前从内部存储中删除文件

3

我希望能在程序运行时删除一个内部文件。当我从外部服务器下载文件时,旧的同名文件会被替换,但我无法读取它。我认为在下载新版本前需要删除旧文件。以下是我目前尝试过的示例代码:

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();
}

这使我能够将文件保存到内部存储器中,但我不确定在写入新版本之前如何删除先前的文件。


File file = new File("somePath"); file.delete(); 文件 file = new File("某个路径"); file.delete(); - Martin Pfeffer
1
在覆盖旧文件之前,您不需要删除它。如果您没有看到新版本,则可能出现其他问题(将其保存到错误的位置,已经打开并且没有重新打开等)。 - Gabe Sechan
1个回答

3

如果您需要确保文件被覆盖,即在保存新版本之前删除旧版本,请使用文件对象的exists()方法。以下是一个示例,展示如何在嵌套目录中删除旧版图像文件并写入具有相同名称的新文件:

// 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();
    }
}

您还需要确保具有内存读写权限,确保在运行时向用户请求这些权限,并在清单文件中添加以下内容:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接