我想知道是否可以将 HttpServletRequest 的传入字节直接写入磁盘而不将其保存在内存中。
Note that I don't want to wait the entire request to complete, but handle partial data independently. Like chunks.
我目前正在使用 JBOSS,只有在整个上传完成后,我才会在 doPost 方法中的 ServletInputStream 中获取这些字节。但我想在读取时从 InputStream 中“读取并删除”这些字节。有大量文件正在上传,我希望按照如下所示的协调流程进行工作:
- InputStream 到达 1024 字节
- 从 InputStream 读取(并删除)1024 字节
- 1024 字节写入输出流(在本例中为 FileOutputStream)
这可能吗?作为原始套接字通信...从而完全避免 OOM。
最佳答案
您可以使用所需大小的 block (缓冲区)来部分读取数据:
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();
关于java - 如何在 Servlet 请求中将传入字节直接写入磁盘?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30399067/