【发布时间】:2015-04-30 13:34:13
【问题描述】:
我正在尝试从存储中删除一个文件,但是当我这样做时它返回 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");
【问题讨论】:
-
你浏览过this链接吗?它的作品完美。
标签: android file directory storage internal