我怎么用番石榴做这个?

时间:2010-09-27 09:18:57

标签: java guava apache-commons

有没有办法使用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)

感谢。

1 个答案:

答案 0 :(得分:12)

首先,一个选项是:

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

我不知道这肯定比在循环中附加更快(显然它也涉及根据行构建另一个字符串),但它读得更好。

对于另外两个...... Guava并没有真正提供任何特定的序列化。也就是说,如果你愿意,你可以在Guava的IO支持之上构建一些不错的实用程序。当您可以直接向/从流中写入/读取对象时,浏览中间byte[]似乎是浪费序列化或反序列化对象。像这样的方法写起来相当容易:

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

Object deserialize(InputSupplier<? extends InputStream> inputSupplier)
    throws IOException, ClassNotFoundException;
相关问题