How to wrap a java.lang.Appendable into a java.io.Writer?

不羁的心 提交于 2019-11-29 15:28:11

Typically in a Writer, the flush() and close() are there to cleanup any additional writes that may not have been committed or sent to the stream. By simply redirecting all of the write methods directly to the append methods in the Appendable you won't have to worry about flush() and close() unless your Appendable implements Closeable and/or Flushable.

A good example is something like BufferedWriter. When you are calling write() on that, it may not be sending all of the bytes to the final output/stream immediately. Some bytes may not be sent until you flush() or close() it. To be absolutely safe, I would test the wrapped Appendable if it is Closeable or Flushable in the corresponding method and cast it and perform the action as well.

This is a pretty standard design pattern called the Adapter pattern.

Here is what is likely a good implementation for this adapter: http://pastebin.com/GcsxqQxj

You can accept any Appendable and then check if it is a Writer through instanceof. Then do a downcast and call that function that accepts only Writer.

example:

public void myMethod(Appendable app) throws InvalidAppendableException {

   if (app instanceof Writer) {
      someObj.thatMethod((Writer) app);
   } else {
      throw new InvalidAppendableException();
   }
}

Google's Guava has a simple utility to do this: CharStreams.asWriter

The implementation is not the fastest (see), if you want the best performance, you might want to look at spf4j Streams.asWriter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!