Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I do this using guava?

Is there a way of achieving the below using Guava?

//anything better than using Files.append() in a loop?
org.apache.commons.io.FileUtils.writeLines(File file, Collection lines, String lineEnding);

//gives a byte[] that is fed to Files.write(byte[] from, File to)
org.apache.commons.lang.SerializationUtils.serialize(Serializable obj) 

//get an object from a byte[] 
SerializationUtils.SerializationUtils.deserialize(byte[] from)

Thanks.

like image 309
anthonyms Avatar asked Sep 27 '10 09:09

anthonyms


1 Answers

For the first, one option would be:

Files.write(Joiner.on(lineEnding).join(lines), file, charset);

I don't know that this would necessarily be faster than appending in a loop (and obviously it involves building another string based on the lines as well), but it reads nicer.

For the other two... Guava doesn't really offer anything specific to serialization. That said, you can build some nice utilities on top of Guava's IO support if you want. Going through an intermediate byte[] seems wasteful for serializing or deserializing objects when you could be writing/reading the objects directly to/from a stream. Methods such as these would be fairly easy to write:

void serialize(OutputSupplier<? extends OutputStream> outputSupplier,
               Object object) throws IOException;

Object deserialize(InputSupplier<? extends InputStream> inputSupplier)
    throws IOException, ClassNotFoundException;
like image 69
ColinD Avatar answered Oct 17 '22 05:10

ColinD