Skip to content

Instantly share code, notes, and snippets.

@schmmd
Created August 29, 2011 21:44
Show Gist options
  • Save schmmd/1179491 to your computer and use it in GitHub Desktop.
Save schmmd/1179491 to your computer and use it in GitHub Desktop.
Pipe a Reader to a Writer or an InputStream to an OutputStream in java.
public class Pipe {
/***
* Writes all lines read from the reader.
* @param reader The source reader
* @param writer The destination writer
* @throws IOException
*/
public static void pipe(Reader reader, Writer writer) throws IOException {
pipe(reader, writer, 4092);
}
/***
* Writes all lines read from the reader.
* @param reader the source reader
* @param writer the destination writer
* @param buffersize size of the buffer to use
* @throws IOException
*/
public static void pipe(Reader reader, Writer writer, int buffersize) throws IOException {
char[] buffer = new char[buffersize];
while (reader.read(buffer) != -1) {
writer.write(buffer);
}
}
/***
* Writes all lines read from the reader.
* @param is The input stream
* @param os The output stream
* @throws IOException
*/
public static void pipe(InputStream is, OutputStream os) throws IOException {
pipe(is, os, 4092);
}
/***
* Writes all lines read from the reader.
* @param is The input stream
* @param os The output stream
* @param buffersize size of the buffer to use
* @throws IOException
*/
public static void pipe(InputStream is, OutputStream os, int buffersize) throws IOException {
byte[] buffer = new byte[buffersize];
while (is.read(buffer) != -1) {
os.write(buffer);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment