InputStreams を使用しているという既存の問題があり、このチャネルからの読み取りのパフォーマンスを向上させたいと考えています。したがって、私は で読みますReadableByteChannel
。
その結果、次のコードを使用すると読み取りがはるかに高速になります。
public static String readAll(InputStream is, String charset, int size) throws IOException{
try(ByteArrayOutputStream bos = new ByteArrayOutputStream()){
java.nio.ByteBuffer buffer = java.nio.ByteBuffer.allocate(size);
try(ReadableByteChannel channel = Channels.newChannel(is)){
int bytesRead = 0;
do{
bytesRead = channel.read(buffer);
bos.write(buffer.array(), 0, bytesRead);
buffer.clear();
}
while(bytesRead >= size);
}
catch(Exception ex){
ex.printStackTrace();
}
String ans = bos.toString(charset);
return ans;
}
}
問題は:毎回最後まで読まない! ファイルを読み取ろうとすると、かなりうまく機能します。ネットワークソケットから読み取ると(たとえば、手動でWebページをリクエストするために)、途中で停止することがあります。
最後まで読むにはどうしたらいいですか?
私はこのようなものを使いたくありません:
StringBuilder result = new StringBuilder();
while(true){
int ans = is.read();
if(ans == -1) break;
result.append((char)ans);
}
return result.toString();
この実装は遅いためです。
私の問題を解決できることを願っています。私のコードに間違いがあるかもしれません。