Skip to content

Instantly share code, notes, and snippets.

@matthewglover
Created October 19, 2017 14:30
Show Gist options
  • Save matthewglover/bc426a322ed5df5fb7a52c3868ab71fc to your computer and use it in GitHub Desktop.
Save matthewglover/bc426a322ed5df5fb7a52c3868ab71fc to your computer and use it in GitHub Desktop.
Java InputStream Adapter
package com.matthewglover.core;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class InputStreamAdapter extends InputStream {
private final int bufferSize = 1024;
private final InputStream adaptedInputStream;
public InputStreamAdapter(InputStream adaptedInputStream) {
this.adaptedInputStream = adaptedInputStream;
}
public void transferTo(OutputStream outputStream) throws IOException {
byte[] buffer = new byte[bufferSize];
while (writeBuffer(outputStream, buffer));
}
@Override
public int read() throws IOException {
return adaptedInputStream.read();
}
private boolean writeBuffer(OutputStream outputStream, byte[] buffer) throws IOException {
int len = read(buffer);
if (len == -1) {
return false;
} else {
outputStream.write(buffer, 0, len);
return true;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment