0

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

4

3 回答 3

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"/>
于 2012-12-25T13:03:13.077 回答
0

你最好使用首选项。写入外部存储通常是个坏主意。使用 SharedPreferences 保存对象的状态并使用您保存的数据再次实例化该对象。

共享偏好 API

于 2012-12-26T02:16:01.757 回答
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();
于 2013-04-07T22:10:14.087 回答