views:

124

answers:

1

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.

+2  A: 

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;
ColinD
tks for th response.
Mjuaji