I'm trying to read all objects from a file and saving it to and array. But, I get a 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.
For example use Gson
library.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.