要保存到一個文件:讓你的類序列化
package com.yourpackage.name;
import java.io.Serializable;
public class myClass implements Serializable {
public enum counterType {
count_down,
count_up
}
public int myIntValue= 0;
}
如果您收到警告「的Serializable類X不聲明static final的serialVersionUID字段類型long',您可以通過爲serialVersionUID添加一個值來解決此問題,例如:
private static final long serialVersionUID = 1234567890abcdefg;
像你一樣聲明你的變量(例如,在您的主要活動):
myClass myClassVariable = new myClass();
myClassVariable.myIntValue = 99;
現在,您可以將數據保存到一個文件中,使用:
try
{
FileOutputStream myFileOutputStream = new FileOutputStream(getFilesDir() + "file_name.ser");
ObjectOutputStream myObjectOutputStream = new ObjectOutputStream(myFileOutputStream);
myObjectOutputStream.writeObject(myClassVariable);
myObjectOutputStream.close();
}
catch (Exception e)
{
Log.e("Error when saving to file.",Log.getStackTraceString(e));
}
要重新加載數據:
try
{
FileInputStream myFileInputStream = new FileInputStream(getFilesDir() + "file_name.ser");
ObjectInputStream myObjectInputStream = new ObjectInputStream(myFileInputStream);
readClassVariable = (myClass) myObjectInputStream.readObject();
myObjectInputStream.close();
}
catch (Exception e)
{
Log.e("Error when loading from file.",Log.getStackTraceString(e));
}
readClassVariable現在包含您保存類,例如readClassVariable.myIntValue等於99
希望它有幫助。評論歡迎:)
P.S.我需要代表,所以不要忘了接受答案,如果你喜歡它!
是否必須輸出到文件?它可以全部在RAM中完成嗎? – Wonson 2014-10-08 07:51:28
是否可以使用ByteArrayOutputStream而不是FileOutputStream? – Wonson 2014-10-08 08:01:24
要保存到RAM,請參閱下面的更新回答... – EddyBee 2014-10-09 09:06:38