代码之家  ›  专栏  ›  技术社区  ›  james

Android:如何删除内部图像文件

  •  10
  • james  · 技术社区  · 16 年前

    我要做的是:从我的应用程序的私有内部存储中删除一个图像文件。我将图像保存在内部存储器中,以便在卸载应用程序时删除。

    我已成功创建并保存:

    String imageName = System.currentTimeMillis() + ".jpeg";
    FileOutputStream fos = openFileOutput(imageName, Context.MODE_PRIVATE);
    bitmap.compress(Bitmap.CompressFormat.JPEG, 35, fos);
    

    我所接收到的图像

    bitmap = BitmapFactory.decodeStream(inputStream);
    

    稍后我可以检索图像进行显示:

    FileInputStream fis = openFileInput(imageName);
    ByteArrayOutputStream bufStream = new ByteArrayOutputStream();
    DataOutputStream outWriter = new DataOutputStream(bufStream);
    
    int ch;
    while((ch = fis.read()) != -1)
        outWriter.write(ch);
    
    outWriter.close();
    byte[] data = bufStream.toByteArray();
    bufStream.close();
    fis.close();
    
    imageBitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
    

    我现在要永久删除此文件。我尝试创建一个新文件并将其删除,但找不到该文件:

    File file = new File(imageName);
    file.delete();
    

    我在Android开发者网站上看到,我必须使用 openFileInput(...) 方法,它返回一个允许我读取内容的输入流,我并不真正关心这些内容-我只想删除它。

    有人能给我指出删除存储在内部存储器中的文件的正确方向吗?

    1 回复  |  直到 16 年前
        1
  •  23
  •   james    16 年前

    厄格,我自己找到了答案。答案也很简单:(

    你只需要打电话给 deleteFile(imageName) 方法。

    if(activity.deleteFile(imageName))
        Log.i(TAG, "Image deleted.");
    

    完成!