[英]How to read multiple objects in a file to an arraylist?
I'm trying to read all objects from a file and saving it to and array. 我正在尝试从文件中读取所有对象,并将其保存到and数组。 But, I get a StreamCorruptedException. 但是,我得到一个StreamCorruptedException。 Another question: it is unrelated : Whenever I view the file with objects stored in it, it's in Object language. 另一个问题:它不相关:每当我查看文件中存储的对象时,它都是使用对象语言。 Is it possible to turn it to human readable language? 可以将其转换为人类可读的语言吗?
public void generateLibReport() throws IOException, FileNotFoundException, ClassNotFoundException{
ObjectInputStream ois = new ObjectInputStream(new
FileInputStream("LibrarianFile.txt"));
boolean check = true;
ArrayList<Librarian> array = new ArrayList();
while(check){
try{
Librarian librarian = (Librarian)ois.readObject();
array.add((Librarian)librarian);
}
catch(EOFException e){
for(Librarian l:array){
System.out.println(l);
}
check = false;
ois.close();
}
}
}
If you want to use readable language, try save objects in JSON
format. 如果要使用可读语言,请尝试以JSON
格式保存对象。
For example use Gson
library. 例如,使用Gson
库。
void save(List<Librarian> libs) {
String json = gson.toJson(libs);
//save json text in simple text file
}
List<Librarian> load(String filename) {
//read text file to json variable
String json = ...;
return gson.fromJson(json, new TypeToken<List<Librarian>>(){});
}
This way solve both questions. 这样可以解决两个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.