我一直在寻找一种从文本文件中读取ArrayList的方法,但我似乎无法让它正常工作。
我已设法使用以下代码将ArrayList保存到文件:
static void saveGameData(ArrayList<GameProfiles> GameProfiles, File GameProfiles_Save) {
try {
FileWriter fw = new FileWriter(GameProfiles_Save);
BufferedWriter output = new BufferedWriter(fw);
for (int i = 0; i < GameProfiles.size(); i++) {
output.write(GameProfiles.get(i).toString());
output.newLine();
}
output.close();
} catch (IOException e) {
System.out.println("I cannot create that file");
}
}
我想现在要做的就是阅读该文件中的文本,并以实例的分析ArrayList
的GameProfiles
。
发布于 2018-08-08 09:51:02
你需要做的是将文件序列化为可以加载和保存的格式。我建议GSON自动获取数据对象并将它们转换为可以再次加载的字符串。你可以使用它来保存你的游戏配置文件数组,如下所示:
static Gson gson=new Gson();
static void saveGameData(List<GameProfiles> gameProfiles, File save) throws IOException {
try (Writer writer = new FileWriter(save)) {
gson.toJson(gameProfiles, writer);
writer.flush();
}
}
加载:
try(FileReader reader=new FileReader(save)){
gameProfiles=gson.fromJson(reader, new TypeToken<List<GameProfiles>>(){}.getType());
}
发布于 2018-08-08 10:01:08
对于你获得的每一行,只需进行处理以创建新的GameProfile,例如使用.split()方法检索每个字段,然后将其添加到你的ArrayList中。
https://stackoverflow.com/questions/-100002002
复制相似问题