Last active
September 18, 2018 08:14
-
-
Save ok3141/6551b61df23b524af1ca45d8c2b638c9 to your computer and use it in GitHub Desktop.
Redirect InputStream to Android Logcat
This file contains hidden or 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
| import android.util.Log; | |
| import java.io.ByteArrayOutputStream; | |
| import java.io.IOException; | |
| import java.io.InputStream; | |
| public final class LoggingInputStream extends InputStream { | |
| static { | |
| if (!BuildConfig.DEBUG) { | |
| throw new AssertionError(); | |
| } | |
| } | |
| private final String logTag; | |
| private final String linePrefix; | |
| private final InputStream inputStream; | |
| private final ByteArrayOutputStream buffer; | |
| public LoggingInputStream(String logTag, String linePrefix, InputStream inputStream) { | |
| this.logTag = logTag; | |
| this.linePrefix = linePrefix; | |
| this.inputStream = inputStream; | |
| this.buffer = new ByteArrayOutputStream(); | |
| } | |
| private void process(int oneByte) { | |
| synchronized (buffer) { | |
| if (oneByte < 0) { | |
| flush(); | |
| } else { | |
| buffer.write(oneByte); | |
| if (Character.LINE_SEPARATOR == (byte) oneByte) { | |
| flush(); | |
| } | |
| } | |
| } | |
| } | |
| private void flush() { | |
| synchronized (buffer) { | |
| if (buffer.size() > 0) { | |
| Log.v(logTag, linePrefix + buffer.toString()); | |
| buffer.reset(); | |
| } | |
| } | |
| } | |
| @Override | |
| public int read() throws IOException { | |
| int oneByte = inputStream.read(); | |
| process(oneByte); | |
| return oneByte; | |
| } | |
| @Override | |
| public void close() throws IOException { | |
| inputStream.close(); | |
| flush(); | |
| } | |
| @Override | |
| public long skip(long n) throws IOException { | |
| return inputStream.skip(n); | |
| } | |
| @Override | |
| public int available() throws IOException { | |
| return inputStream.available(); | |
| } | |
| @Override | |
| public void mark(int readlimit) { | |
| inputStream.mark(readlimit); | |
| } | |
| @Override | |
| public void reset() throws IOException { | |
| inputStream.reset(); | |
| } | |
| @Override | |
| public boolean markSupported() { | |
| return inputStream.markSupported(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment