簡體   English   中英

如果我使用 ReadableByteChannel 和 BufferedReader,如何讀取 InputStream 兩次?

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

如果我使用ReadableByteChannelBufferedReader如何讀取InputStream兩次?

這是我的代碼:

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());

您已經編寫了大量代碼來將input復制到兩個目的地: outputjsonResponse 由於您已經制作了input => bytes的內存副本,因此不需要掃描input兩次,並且您不需要使用IOUtils來簡單復制到 byte[],您可以重新使用它發送到兩個目的地:

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

然后按照@g00se 的建議進行操作 - 如果字符編碼是平台默認值:

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

您還應該處理關閉輸入/輸出流,最好使用 try-with-resources 塊完成。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM