开发者

How do I do this using guava?

开发者 https://www.devze.com 2023-01-17 22:42 出处:网络
Is there a way of achieving the below using Guava? //anything开发者_JAVA技巧 better than using Files.append() in a loop?

Is there a way of achieving the below using Guava?

//anything开发者_JAVA技巧 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.


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;
0

精彩评论

暂无评论...
验证码 换一张
取 消