Reputation: 230
I am trying to read and write an ArrayList to a file, and currently using ObjectOutputStream to write to the file.
fout = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(arraylist);
fout.close();
The arraylist
variable is an ArrayList of ojects. This method works fine and all, but it prints to the file in a format that is not human-readable.
Is there any way to achieve the same functionality (with relative ease) so that the object is written to the file in a human-readable manner?
Upvotes: 3
Views: 744
Reputation: 53839
You can use a Json representation, which is human readable.
For instance using Jackson:
ObjectWriter ow = new ObjectMapper().writer();
ow.writeValue(fout, arraylist);
To read back:
List<E> myObjects = new ObjectMapper().readValue(inputStream,
new TypeReference<List<E>>(){});
Upvotes: 4
Reputation: 1133
Since you are using ObjectOutputStream
,it writes a binary serialized version of that data to file ,which is non-human readable. However you can use BufferedWriter
for performing the same.
//Sample code
try{
ArrayList<YourObject> yourObjectList;
BufferedWriter writer = new BufferedWriter(new FileWriter("C:/yourPath/fileName.txt"));
for (YourObject oneObjAtATime : yourObjectList) {
writer.write(oneObjAtATime.toString());
}
}catch(Exception e){
throw new Exception("error");
}
Upvotes: 2
Reputation: 972
I think what you need to do is use a PrintWriter, and cycle through your array list printing to the new file each time. Try:
PrintWriter writer = new PrintWriter(outputFile);
for (int i=0;i<<name>.length;i++){
writer.println(<ArrayListName>[i].getString(), + "\t" + <ArrayListName>[i].getFirstInt() + "\t" + <name>.[i].getSecondInt +<etc...>);
}
Hope this helps!
Upvotes: 3