Javaのメモリに完全にコピーするのではなく、ブロックで書き込んでください。以下の基本的な例では、それを10KB単位で書き込みます。この方法では、完全なコンテンツ長ではなく、わずか10KBの一貫したメモリ使用量になります。また、エンドユーザは、コンテンツの一部をずっと早く取得し始めます。パフォーマンスに関してクレームデラクレームとして
response.setContentLength(getContentLength());
byte[] buffer = new byte[10240];
try (
InputStream input = getInputStream();
OutputStream output = response.getOutputStream();
) {
for (int length = 0; (length = input.read(buffer)) > 0;) {
output.write(buffer, 0, length);
}
}
、あなたはNIO Channels
を使用することができますし、直接ByteBuffer
を割り当てられました。いくつかのカスタムユーティリティクラスで、次のユーティリティ/ヘルパーメソッドを作成します。 Utils
:あなたは以下のように使用し
public static long stream(InputStream input, OutputStream output) throws IOException {
try (
ReadableByteChannel inputChannel = Channels.newChannel(input);
WritableByteChannel outputChannel = Channels.newChannel(output);
) {
ByteBuffer buffer = ByteBuffer.allocateDirect(10240);
long size = 0;
while (inputChannel.read(buffer) != -1) {
buffer.flip();
size += outputChannel.write(buffer);
buffer.clear();
}
return size;
}
}
:
response.setContentLength(getContentLength());
Utils.stream(getInputStream(), response.getOutputStream());
私はそこに別の方法があることを望んでいましたが、とにかく感謝します –
ありがとうございます。BalusC、 –
もちろん、多くのユーティリティパッケージにはこのメソッドが既に定義されていますので、Guavaを使用し始めるとhttp://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io /ByteStreams.html#copy(java.io.InputStream、java.io.OutputStream) –