且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将自定义对象的ArrayList写入File

更新时间:2022-10-16 16:22:42

我会建议使用序列化进行这样的操作。你可以实现Java的Serializable接口,然后你可以将你的对象压缩成一个.ser文件,然后从这个文件中将它们膨胀回来,从而调用你需要的方法。

这是一个关于序列化的好教程 - http://www.tutorialspoint.com/java/java_serialization.htm


I have an ArrayList which contains custom Service objects. I want to write the whole ArrayList to a File and be able to read it afterwards.

I tried Gson for that, but it gives me a IllegalStateException: Expected BEGIN_ARRAY but was STRING. I let it log me the Strings of what should be JSON and it said a lot of Exceptions in it (as a text inside the String.. maybe the conversion has gone wrong?).

public int saveListToFile(){
        String filename = "service_entries";
        File file = new File(getFilesDir(), filename);
        try {
            BufferedWriter buffWriter = new BufferedWriter(new FileWriter(file, true));

            Gson gson = new Gson();
            String json = gson.toJson(services); //this is the ArrayList<Service>

            buffWriter.append(json);
            buffWriter.newLine();
            buffWriter.close();
        } catch (IOException e) {
            return -1;
        }

        return 0;
}

public int readCurrentList(){   
        String filename = "service_entries";

        File file = new File(getFilesDir(), filename);  
        try {
            BufferedReader buffReader = new BufferedReader(new FileReader(file));

            String line1, line2;
            Gson gson = new Gson();

            line1 = buffReader.readLine();
            line2 = buffReader.readLine();

            if(line1 == null){
                buffReader.close();
                return 0;
            }

            Type type = new TypeToken<ArrayList<Service>>(){}.getType();
            services = gson.fromJson(line1, type);

            ArrayList<Service> list2;
            if(line2 != null){
                list2 = gson.fromJson(line2, type);

                services.addAll(list2);
                list2 = null;
            }

            buffReader.close();
        } catch(IOException e){
            return -1;
        }

        return 0;
}

public class Service {

        private double quantity;
        private String description;

        public Service(){
            quantity = 0.0;
            description = null;
        }

}

I would recommend using serialization for such an operation. You can implement Java's Serializable interface and you are then able to deflate your objects into a .ser file and then inflate them back from that very file to call the methods you need from them.

Here is a nice tutorial regarding Serialization - http://www.tutorialspoint.com/java/java_serialization.htm