要保存到一个文件:让你的类序列化
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