我的项目直到从未需要保存数据,所以这是我第一次保存数据。我想要做的是保存基于类的数组列表中的数据。我见过几个人用几个不同的答案问这个,但我似乎错过了一些东西。这是在我所有尝试之后代码被删除的内容。我希望有人可以帮助我如何保存和加载此信息。几乎忘了这是应用程序的配置文件保存,因此如果用户选择,可以有多个文件。
//in manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
//in java file
private ArrayList<otherclass> otherClass=new ArrayList<otherclass>();
class saveData
{
static private final int version=101002;
private String title;
private int[] Int1=new int[3];
private int[] Int2=new int[3];
private int[] Int3=new int[3];
private int Int;
}
class otherclass
{
//all the data goes here to similar named variables
}
答案 0 :(得分:2)
一种方法是将要添加到ArrayList的类实现可序列化。如果你的类只是由同时实现serializable的对象组成,那么你就完成了(这很可能就是这种情况),只需添加如下的implements Serializable:
public class myClass implements Serializable {
否则,您需要将以下两种方法添加到您的班级
private void writeObject(java.io.ObjectOutputStream out) throws IOException
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException
添加实现Serialible让ObjectOutStream知道它可以序列化您的数据以进行存储:
然后,您可以实施以下方法来保存和打开您的数据,请参阅每个步骤的注释...
void saveArray(String filename, ArrayList<myClass> arrayToSave) {
FileOutputStream fos; //creates a file output stream to save your data
ObjectOutputStream oos; //creates an object output stream to serialize your data
try {
fos = openFileOutput(filename, Context.MODE_PRIVATE); //creates and opens file with the specified filename, Context.MODE_PRIVATE limits its visibility to your app, other modes are available
oos = new ObjectOutputStream(fos); //connects object output to file output
oos.writeObject(arrayToSave); //writes the object to the file
}
catch (FileNotFoundException e) {
//handle file not found
}
catch (IOException e) {
}
//handle I/O execption
oos.close(); //close object output stream
fos.close(); //close file output stream
}
ArrayList<myClass> openArray (String filename) {
ArrayList<myClass> array = null; //create ArrayList
FileInputStream fis; //create fileinput stream
ObjectInputStream ois; //create objet input stream
try {
fis = openFileInput(filename); //open file stream
ois = new ObjectInputStream(fis); //open object stream
array = (ArrayList<myClass>)ois.readObject(); //create object from stream
}
catch (Exception e) {
System.out.println(e.toString());
}
ois.close(); //close objectinput stream
fis.close(); //close fileinput stream
return array;
}
最后,两个文件输入/输出流都可以包装在bufferedinputstream / bufferedoutput流中,但我发现它对小文件的影响不大。这可以通过
完成 BufferedInputStream bufIn = new BufferedInputStream(new FileInputStream("file.java"));
BufferedOutputStream bufOut = new BufferedOutputStream(new FileInputStream("file.java"));
好吧,下面是一个完整的活动文件来说明这个并且已经使用2.1版进行了测试...您需要更改的唯一内容是与您的项目匹配的包名称...请注意,这会更改saveData中的变量从私有包,如果你想保持私有,你可能应该,你需要实现setter / getters,但下面的代码应该帮助你理解保存/加载对象......
package youpackage.name.myapp;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
class saveData implements Serializable {
private static final long serialVersionUID = 1L;
private final int version = 101002;
String title;
int[] Int1 = new int[3];
int[] Int2 = new int[3];
int[] Int3 = new int[3];
int Int;
}
public class MyAppActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
System.out.println("This next line creates instance of class to save");
saveData mySaveData = new saveData();
System.out.println("This next line sets the title...");
mySaveData.title = "accept my answer...";
ArrayList<saveData> myArrayList = new ArrayList<saveData>();
System.out.println("This next line adds the object to the ArrayList");
myArrayList.add(mySaveData);
System.out.println("This next line saves the arraylist");
saveArray("myFilename", myArrayList);
System.out.println("This next line loads the arraylist back...");
ArrayList<saveData> retrieveArrayList = openArray("myFilename");
if (retrieveArrayList.size() > 0) {
saveData retrievedSaveData = retrieveArrayList.get(0);
System.out.println("if successful, the title set above will appear...");
System.out.println("if save/retrieve works, then " + retrievedSaveData.title);
}
else {
System.out.println("it did not work");
}
}
void saveArray(String filename, ArrayList<saveData> arrayToSave) {
FileOutputStream fos;
ObjectOutputStream oos;
try {
fos = openFileOutput(filename, Context.MODE_PRIVATE);
oos = new ObjectOutputStream(fos);
oos.writeObject(arrayToSave);
oos.close();
fos.close();
} catch (Exception e) {
System.out.println(e.toString());
}
}
ArrayList<saveData> openArray (String filename) {
ArrayList<saveData> array = null;
FileInputStream fis;
ObjectInputStream ois;
try {
fis = openFileInput(filename);
ois = new ObjectInputStream(fis);
array = (ArrayList<saveData>)ois.readObject();
ois.close();
fis.close();
} catch (Exception e) {
System.out.println(e.toString());
}
return array;
}
}
正如我在上一篇文章中提到的,以下更新的加载和保存方法可以提高性能......
void saveArray2(String filename, ArrayList<saveData> arrayToSave) {
try {
BufferedOutputStream bos = new BufferedOutputStream(openFileOutput(filename, Context.MODE_PRIVATE),8000);
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(arrayToSave);
oos.close();
} catch (Exception e) {
System.out.println(e.toString());
}
}
ArrayList<saveData> openArray2 (String filename) {
ArrayList<saveData> array = null;
try {
BufferedInputStream bufIn = new BufferedInputStream(openFileInput(filename),8000);
ObjectInputStream ois = new ObjectInputStream(bufIn);
array = (ArrayList<saveData>)ois.readObject();
ois.close();
} catch (Exception e) {
System.out.println(e.toString());
}
return array;
}
答案 1 :(得分:1)
我刚刚将您的私人会员改为公开会员。你不希望你需要获取值的getter和setter。我也不知道你对最终静态版本成员的要求......但这是一个很好的方法:
包含数据的类
class otherClass {
static private final int version=101002;
public String title;
public int[] Int1=new int[3];
public int[] Int2=new int[3];
public int[] Int3=new int[3];
public int Int;
}
读取/写入数据的类
class saveData {
public boolean write(ArrayList<otherClass> list, String fileName) {
try {
FileutputStream fos = new FileOutputStream(fileName);
DataOutputStream dos = new DataOutputStream(fos);
final int length = list.size();
for (int i = 0; i < length; i++) {
otherClass item = list.get(i);
dos.writeUTF(item.title);
dos.writeInt(item.Int1[0]);
dos.writeInt(item.Int1[1]);
dos.writeInt(item.Int1[2]);
dos.writeInt(item.Int2[0]);
dos.writeInt(item.Int2[1]);
dos.writeInt(item.Int2[2]);
dos.writeInt(item.Int3[0]);
dos.writeInt(item.Int3[1]);
dos.writeInt(item.Int3[2]);
dos.writeInt(item.Int);
}
dos.close();
fos.close();
return true;
} catch (IOException e) {
return false;
}
}
public ArrayList<otherClass> read(String fileName) {
try {
FileInputStream fos = new FileInputStream(fileName):
DataInputStream dis = new DataInputStream(fis);
ArrayList<otherClass> list = new ArrayList<otherClass>();
while (dis.available() > 0) {
otherClass item = new otherClass();
item.title = dis.readUTF();
item.Int1[0] = dis.readInt();
item.Int1[1] = dis.readInt();
item.Int1[2] = dis.readInt();
item.Int2[0] = dis.readInt();
item.Int2[1] = dis.readInt();
item.Int2[2] = dis.readInt();
item.Int3[0] = dis.readInt();
item.Int3[1] = dis.readInt();
item.Int3[2] = dis.readInt();
item.Int = dis.readInt();
list.add(item);
}
return list;
} catch (IOException e) {
return null;
}
}
}
示例用法
saveData.write(list, "someFile");
list = saveData.read("someFile");