java arraylist 写入文件_java-将自定义对象的ArrayList写入文件
发布日期:2021-06-24 16:15:16 浏览次数:4 分类:技术文章

本文共 1319 字,大约阅读时间需要 4 分钟。

我有一个包含自定义服务对象的ArrayList.我想将整个ArrayList写入一个文件,然后可以读取它.

我为此尝试了Gson,但它给了我一个IllegalStateException:预期为BEGIN_ARRAY,但为STRING.我让它记录了应该是JSON的Strings,并在其中表示了很多异常(作为String中的文本..也许转换出错了吗?).

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

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>(){}.getType();

services = gson.fromJson(line1, type);

ArrayList 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;

}

}

转载地址:https://blog.csdn.net/weixin_33758343/article/details/114092456 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:ice glacier2 java_ICE提纲之demo/Glacier2/callback(跨网回调)
下一篇:java 设置http响应_JAVA发送HTTP请求,返回HTTP响应内容,应用及实例代码

发表评论

最新留言

路过按个爪印,很不错,赞一个!
[***.219.124.196]2024年04月13日 19时03分37秒