简体   繁体   English

如果我使用 ReadableByteChannel 和 BufferedReader,如何读取 InputStream 两次?

[英]How to read InputStream twice if I am using ReadableByteChannel and BufferedReader?

How to read an InputStream twice if I am using ReadableByteChannel and BufferedReader ?如果我使用ReadableByteChannelBufferedReader如何读取InputStream两次?

Here is my code:这是我的代码:

ReadableByteChannel inputChannel = Channels.newChannel(input);
WritableByteChannel outputChannel = Channels.newChannel(output);

InputStream ind = Channels.newInputStream(inputChannel);
ReadableByteChannel inputChannel1 = Channels.newChannel(ind);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
org.apache.commons.io.IOUtils.copy(ind, baos);
ByteBuffer buffer = ByteBuffer.allocateDirect(10240);
long size = 0;
while (inputChannel1.read(buffer) != -1) {
    buffer.flip();
    size += outputChannel.write(buffer);
    buffer.clear();
}

byte[] bytes = baos.toByteArray();
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
BufferedReader in = new BufferedReader(new InputStreamReader(bais));
String inputLine;
StringBuffer bufferResponse = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
    bufferResponse.append(inputLine);
}
JSONObject jsonResponse = new JSONObject(bufferResponse.toString());

You've written a lot of code to copy input to two destinations: output and jsonResponse .您已经编写了大量代码来将input复制到两个目的地: outputjsonResponse As you have made an in-memory copy of input => bytes there is no need to scan input twice, and you don't need to use IOUtils for a simple copy to byte[] which you can re-use to send to the two destinations:由于您已经制作了input => bytes的内存副本,因此不需要扫描input两次,并且您不需要使用IOUtils来简单复制到 byte[],您可以重新使用它发送到两个目的地:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
input.transferTo(baos);
byte[] bytes = baos.toByteArray();
output.write(bytes);

Then do as @g00se suggests - if the char encoding is platform default:然后按照@g00se 的建议进行操作 - 如果字符编码是平台默认值:

String s = new String(bytes /*, or insert another charset here */);
JSONObject jsonResponse = new JSONObject(s);

You should also deal with closing the input/output streams, best done with try-with-resources block.您还应该处理关闭输入/输出流,最好使用 try-with-resources 块完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM