我想知道是否可以将HttpServletRequest的传入字节直接写入磁盘而不将其保存在内存中。
请注意,我不想等待整个请求完成,而是独立处理部分数据。像块一样。
我目前正在使用JBOSS,只有在整个上传完成后,才能在doPost方法中的ServletInputStream上获得这些字节。但是我想在读取时从InputStream中“读取并删除”这些字节。有大量文件正在上传,我希望以协调的方式工作,如下所示:
1024字节到达InputStream
从InputStream读取(和删除)1024字节
1024字节写入Outputstream(在本例中为FileOutputStream)
那可能吗?用作原始套接字通信...因此完全避免了OOM。
最佳答案
您可以使用所需大小的块(缓冲区)来部分读取数据:
BufferedInputStream bis = new BufferedInputStream(yourInputStream);
BufferedOutputStream bos = new BufferedOutputStream(yourFileOutputStream);
final int FILE_CHUNK_SIZE = 1024 * 4; //easier to change to 8 KBs or any other size you want/need
byte[] chunk = new byte[FILE_CHUNK_SIZE];
int bytesRead = 0;
while ((bytesRead = input.read(chunk)) != -1) {
bos.write(chunk, 0, bytesRead);
}
bos.close();
bis.close();