Android从存储OutputStream删除文件

时间:2015-02-27 18:27:06

标签: android file directory storage internal

我正在尝试从存储中删除文件,但是当我这样做时它返回true,因为它已被删除但在下次启动时读取文件就好像它仍然存在:/

    package com.example.Mazer.Utilities;

import android.app.Activity;
import android.content.Context;
import android.util.Log;

import java.io.*;

public class ObjectSaver {

    public static void writeObjectToFile(Context c, Object object, String filename) {

        ObjectOutputStream objectOut = null;
        try {
            FileOutputStream fileOut = c.getApplicationContext().openFileOutput(filename, Activity.MODE_WORLD_READABLE);
            objectOut = new ObjectOutputStream(fileOut);
            objectOut.writeObject(object);
            fileOut.getFD().sync();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (objectOut != null) {
                try {
                    objectOut.close();
                } catch (IOException e) {
                    Log.d("GameActivity", "Can't close objectOut ObjectOutputStream");
                }
            }
        }
    }

    public static void deleteObjectFromFile(Context c, String filename) {
        c.deleteFile( filename);
        //NOPE

        c.getApplicationContext().deleteFile(filename);
        //NOPE

        String s = c.getFilesDir().getAbsolutePath() + "/" + filename;
        c.deleteFile(s);
        //NOPE

    }


    public static Object readObjectFromFile(Context c, String filename) {

        ObjectInputStream objectIn = null;
        Object object = null;
        try {
            FileInputStream fileIn = c.getApplicationContext().openFileInput(filename);
            objectIn = new ObjectInputStream(fileIn);
            object = objectIn.readObject();
        } catch (FileNotFoundException e) {
            return null;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (objectIn != null) {
                try {
                    objectIn.close();
                } catch (IOException e) {
                    // do nowt
                }
            }
        }

        return object;
    }

}

正如您所看到的,我已经添加了我尝试过的百万种方法中的一些,我甚至尝试过度编写文件。

我从文件中读取如下:

maze = (Maze) ObjectSaver.readObjectFromFile(Splash.this, "currentMaze");

和...我保存到这样的文件..

ObjectSaver.writeObjectToFile(context, new Maze(this), "currentMaze");

2 个答案:

答案 0 :(得分:0)

这可能会有所帮助:

import java.io.File;


 public static void deleteObjectFromFile(Context c, String filename) {

      File file = new File(fileName);
      if (file.exists()) { 
         file.delete();
      } 

    }

答案 1 :(得分:0)

boolean deleted = false;

File file = new File(selectedFilePath);
if (file.exists())
deleted = file.delete();

其中selectedFilePath是您要删除的文件的路径 - 例如: /sdcard/MyFolder/example.mp3