文件stream使用Java类似于node.js

我正在讨论一个nodejs教程,它提到Node.JS在将文件写入磁盘时不会将文件保留在内存中,并且会在接收到文件时将文件块刷新到磁盘。 Java是否能够以类似的方式处理文件,或者在冲洗到磁盘之前将整个文件保存在内存中? 在过去,当我尝试使用servlet上传文件时,我遇到了内存exception。

答案是肯定的,在Java中,你可以使用streamAPI,可以帮助你做到这一点。 尝试下面的指南来更好地理解它: http : //commons.apache.org/proper/commons-fileupload/streaming.html

示例:使用Servlet的Fileupload:

// 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 ... } } 

最后,您可以使用以下方法将inputstream写入文件中:

 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();