关闭手机时存储对象文件,并在手机重新启动时检索文件

时间:2012-12-25 12:51:28

标签: android android-file

我已经在我的应用程序的文件中保存了一个类的对象,当手机关闭时,该文件会发生什么?我想,文件丢失了。因为重新启动手机后,我从文件中获取空值(保存在类对象中的某些变量中)。我怎样才能确保,如果手机关机,文件不会丢失。有可能吗?

3 个答案:

答案 0 :(得分:1)

您可以尝试以下代码:

String filename = "filename.txt";
File file = new File(Environment.getExternalStorageDirectory(), filename);
FileOutputStream fos;
byte[] data = new String("data to write to file").getBytes();
try {
    fos = new FileOutputStream(file);
    fos.write(data);
    fos.flush();
    fos.close();
} catch (FileNotFoundException e) {
    // handle exception
} catch (IOException e) {
    // handle exception
}

并确保您已在清单文件中声明了权限

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

答案 1 :(得分:0)

最好使用偏好设置。写入外部存储通常是一个坏主意。使用SharedPreferences保存对象的状态,并使用您保存的数据再次实例化该对象。

SharedPreferences API

答案 2 :(得分:0)

首先我将我的课程序列化为:

public class MyStore implements Serializable {
    //this serialVersionUID will automatically generate
    private static final long serialVersionUID = 3487640153579137276L;
......
......
}

然后我将对象保存在内部存储器中,如下所示:

File path = new File(getActivity().getFilesDir(), foldar_name);
path.mkdirs();
File file = new File(path,file_name);
file.createNewFile();

MyStore myStore = new MyStore();                            
myStore.setData(my_data);

FileOutputStream fout = new FileOutputStream(file);
ObjectOutputStream os = new ObjectOutputStream(fout);
os.writeObject(myStore);
os.flush();
os.close();