Created
October 19, 2017 14:30
-
-
Save matthewglover/bc426a322ed5df5fb7a52c3868ab71fc to your computer and use it in GitHub Desktop.
Java InputStream Adapter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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