我创建了一个扩展 CiphetInputStream 的 InputStream 类。我想记录来 self 的 InputStream 的所有数据(我进一步将其用作解析器中的输入),因此我完成了以下操作:
public class MyInputStream extends CipherInputStream {
private OutputStream logStream = new ByteArrayOutputStream();
.....
@Override
public int read() throws IOException {
int read = super.read();
logStream.write(read);
return read;
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
int read = super.read(b, off, len);
if (read > 0) {
logStream.write(b, off, read);
}
return read;
}
@Override
public int read(byte[] buffer) throws IOException {
int read = super.read(buffer);
if (read()>0) {
logStream.write(buffer);
}
return read;
}
@Override
public void close() throws IOException {
log();
super.close();
}
public void log() {
String logStr = new String(((ByteArrayOutputStream) logStream).toByteArray(), Charset.defaultCharset());
Log.d(getClass(), logStr);
try {
logStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
实际上我的流有这样的内容:
<response>
<result>0</result>
</response>
但是日志显示这样的突变:
<<response>
<resultt >0</resullt>
</respoonse>
[and (?) symbol at the end]
感谢您的帮助!
最佳答案
您可以组合TeeInputStream
和 Logger.stream()
:
new TeeInputStream(
yourStream,
Logger.stream(Level.INFO, this)
);
关于java - 记录输入流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16434699/