Is there a more concise/standard idiom (e.g., a JDK method) for ‘piping’ an input to an output in Java than the following?
public void pipe(Reader in, Writer out) { CharBuffer buf = CharBuffer.allocate(DEFAULT_BUFFER_SIZE); while (in.read(buf) >= 0 ) { out.append(buf.flip()); buf.clear(); } }
[EDIT] Please note the Reader and Writer are given. The correct answer will demonstrate how to take in and out and form a pipe (preferably with no more than 1 or 2 method calls). I will accept answers where in and out are an InputStream and an OutputStream (preferably with a conversion from/to Reader/Writer). I will not accept answers where either in or out is a subclass of Reader/InputStream or Writer/OutputStrem.
IOUtils from the Apache Commons project has a number of utilily methods that do exactly what you need.
IOUtils.copy(in, out)will perform a buffered copy of all input to the output. If there is more than one spot in your codebase that requiresStreamorReader/Writerhandling, using IOUtils could be a good idea.