gpt4 book ai didi

java - Android应用程序在完全退出(从任务管理器退出)时删除文件

转载 作者:行者123 更新时间:2023-12-01 14:46:45 26 4
gpt4 key购买 nike

我有一个尝试从 iOS 项目改编的数据存储类。它适用于 iOS,并且几乎适用于我的 Android 项目,但是,当从任务管理器退出 Android 应用程序时,该文件不会在下次运行时恢复。

该类的目的是如果保存对象时没有文件,该类将创建文件并保存它。如果存在文件,该类将打开该包含数组的文件,将对象附加到该数组,然后保存它。

我是否缺少某些东西来将文件保存到设备上?

这就是我调用类来保存文件的方式

ObjectStore.defaultStore().saveObject(getApplicationContext(), anObject);

这是我的 ObjectStore 类

public class ObjectStore {

ArrayList<Object> objectList = new ArrayList<Object>();
static ObjectStore defaultStore = null;
Context context = null;

public static ObjectStore defaultStore(){
if(defaultStore == null){
defaultStore = new ObjectStore();
}
return defaultStore;
}

public Object ObjectStore(){
if(defaultStore != null){
return defaultStore;
}
return this;
}

public ArrayList<Object> objectList(){
return objectList;
}

public Object saveObject(Context c, Object object){
context = c;
objectList.add(object);
saveFile(context);
return object;
}

public void clearAll(){
objectList.clear();
saveFile(context);
}

public boolean doesFileExist(Context c){
context = c;
File file = c.getFileStreamPath("objectList.file");
if(file.exists()){
return true;
}else{
return createFile(context);
}
}

public boolean createFile(Context c){
context = c;
try{
FileOutputStream fos = context.openFileOutput("objectList"+".file", Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(objectList);
oos.close();
return true;
}catch(IOException e){
e.printStackTrace();
Log.d("TAG", "Error creating file: " + e);
return false;
}
}

public boolean saveFile(Context c){
Log.d("TAG", "Trying to save file");
context = c;
try{
FileOutputStream fos = context.openFileOutput("objectList.file", Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(objectList);
oos.close();
Log.d("TAG", "File Saved");
return true;
}catch(IOException e){
e.printStackTrace();
Log.d("TAG", "Error saving file: " + e);
return false;
}
}

@SuppressWarnings("unchecked")
public ArrayList<Object> loadFile(Context c) throws Exception{
Log.d("TAG", "Trying to load file");
context = c;
if(doesFileExist(context)){
try{
FileInputStream fis = context.openFileInput("objectList.file");
ObjectInputStream in = new ObjectInputStream(fis);
objectList = (ArrayList<Object>) in.readObject();
in.close();
Log.d("TAG", "File Loaded");
return objectList;
}catch(IOException e){
e.printStackTrace();
Log.d("TAG", "Error loading file: " + e);
return null;
}
}
return null;
}
}

最佳答案

你的loadFile()永远不会被调用!里面没有任何东西可以调用它! ;)

关于java - Android应用程序在完全退出(从任务管理器退出)时删除文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15376401/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com