使用类似于node.js的Java文件流
我正在浏览一个nodejs教程,其中提到Node.JS在将文件写入磁盘时不会将文件保存在内存中,并且在收到文件时会将文件块刷新到磁盘。Java是否能够以类似的方式处理文件,还是在刷新到磁盘之前将整个文件保存在内存中?在过去,当我尝试使用servlet上传文件时,我遇到了内存不足的异常。答案是肯定的,在java中,您可以使用流式API来帮助您实现这一点。 请尝试以下指南以更好地理解它: 例如: 使用Servlet进行文件上载:使用类似于node.js的Java文件流,java,node.js,Java,Node.js,我正在浏览一个nodejs教程,其中提到Node.JS在将文件写入磁盘时不会将文件保存在内存中,并且在收到文件时会将文件块刷新到磁盘。Java是否能够以类似的方式处理文件,还是在刷新到磁盘之前将整个文件保存在内存中?在过去,当我尝试使用servlet上传文件时,我遇到了内存不足的异常。答案是肯定的,在java中,您可以使用流式API来帮助您实现这一点。 请尝试以下指南以更好地理解它: 例如: 使用Servlet进行文件上载: // Check that we have a file uploa
// Check that we have a file upload request
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
现在,我们准备将请求解析为其组成项。我们是这样做的:
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload();
// Parse the request
FileItemIterator iter = upload.getItemIterator(request);
while (iter.hasNext()) {
FileItemStream item = iter.next();
String name = item.getFieldName();
InputStream stream = item.openStream();
if (item.isFormField()) {
System.out.println("Form field " + name + " with value " + Streams.asString(stream) + " detected.");
} else {
System.out.println("File field " + name + " with file name " + item.getName() + " detected.");
// Process the input stream
...
}
}
最后,您可以使用以下方法将输入流写入文件:
FileOutputStream fout= new FileOutputStream ( yourPathtowriteto );
BufferedOutputStream bout= new BufferedOutputStream (fout);
BufferedInputStream bin= new BufferedInputStream(stream);
int byte;
while ((byte=bin.read()) != -1)
{
bout.write(byte_);
}
bout.close();
bin.close();
非常感谢您流远远超出了Java或NodeJS。在过去,内存要珍贵得多,所以你甚至无法想象新程序员会犯的常见错误,即将所有东西都保存在内存中。谢谢@Kayaman!