0

我的项目直到永远不需要保存数据,所以这是我第一次保存数据。我想做的是从基于类的数​​组列表中保存数据。我见过几个人用几个不同的答案问这个问题,但我似乎遗漏了一些东西。在我所有尝试之后,这就是代码被剥离的内容。我希望有人可以帮助我保存和加载这些信息。差点忘了这是应用程序的配置文件保存,因此如果用户选择,可以有多个文件。

//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
}
4

2 回答 2

2

一种方法是让您添加到 ArrayList 的类实现可序列化。如果您的类仅由也实现可序列化的对象组成,那么您就完成了(很可能是这种情况),只需像这样添加实现可序列化:

 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 bufIn = new BufferedInputStream(new FileInputStream("file.java"));
  BufferedOutputStream bufOut = new BufferedOutputStream(new FileInputStream("file.java"));

好的,下面是一个完整的活动文件来演示这一点,并且已经用 2.1 版进行了测试...您唯一需要更改的是包名称以匹配您的项目...请注意,这会将 saveData 中的变量更改为 package from私有的,如果你想让它们保持私有,你可能应该这样做,你需要实现 setter/getter,但是下面的代码应该可以帮助你理解保存/加载对象......

 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; 
} 
于 2012-04-19T22:44:20.353 回答
1

我刚刚将您的私人成员更改为公共成员。你不希望你需要获取器和设置器来获取值。我也不知道你想要什么最终的静态版本成员......但这是一个好方法:

包含数据的类

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");
于 2012-04-20T18:42:17.347 回答