简体   繁体   中英

ObjectOutputStream human-readable

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?

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

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!

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");
            }

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM