Java 文件和InputStream/OutputStream
你好,Stack Overflow社区 我正在使用Javaservlet对接收到的一些数据进行多步骤处理。当前的过程是使用Apache File Upload将文件输入到服务器,并将其转换为Java 文件和InputStream/OutputStream,java,Java,你好,Stack Overflow社区 我正在使用Javaservlet对接收到的一些数据进行多步骤处理。当前的过程是使用Apache File Upload将文件输入到服务器,并将其转换为文件。然后,一旦用数据填充了input1,我就会运行类似的流程(流程函数是xsl转换): File input1=新文件(文件名);// 只需将FileOutputStream替换为ByteArrayInputStream即可,反之亦然 例如: ByteArrayOutputStream out = new
文件
。然后,一旦用数据填充了input1
,我就会运行类似的流程(流程函数是xsl转换):
File input1=新文件(文件名);// 只需将FileOutputStream
替换为ByteArrayInputStream
即可,反之亦然
例如:
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
我不知道如果你真的不需要,为什么你要用ApacheCommons转换检索到的数据。您可以使用每个FileItem
必须使用和读取上传文件内容的InputStream
:
// create/retrieve a new file upload handler
ServletFileUpload upload = ...;
// parse the request
List<FileItem> items = (List<FileItem>) upload.parseRequest(request);
/* get the FileItem from the List. Yes, it's not a best practice because you must verify
how many you receive, and check everything is ok, etc.
Let's suppose you've done it */
//...
FileItem item = items.get(0);
// get the InputStrem to read the contents of the file
InputStream is = item.getInputStream();
//创建/检索新的文件上载处理程序
ServletFileUpload上传=。。。;
//解析请求
List items=(List)upload.parseRequest(request);
/*从列表中获取FileItem。是的,这不是最佳实践,因为您必须验证
你收到多少,检查一切是否正常,等等。
让我们假设你已经做到了*/
//...
FileItem=items.get(0);
//获取InputStrem以读取文件的内容
InputStream=item.getInputStream();
最后,您可以使用InputStream
对象来读取客户端发送的上传流,从而避免不必要的实例化
是的,建议使用缓冲类,如BufferedInputStream
和BufferedOutputStream
另一个想法是避免使用FileOutputStream
(中间的一个),如果不需要在磁盘中写入(总是比在内存中工作慢),则使用ByteArrayOutputStream
替换它
// All bytes from an InputStream at once
byte[] result = new ByteArrayInputStream(buf)
.readAllBytes();
// Directly redirect an InputStream to an OutputStream
new ByteArrayInputStream(buf)
.transferTo(System.out);
我查看了BufferedStream上的文档。。。这一行是不是InputStream read1=新文件InputStream(out)
使用文件输入流(FileDescriptor fdObj)
构造函数?
// All bytes from an InputStream at once
byte[] result = new ByteArrayInputStream(buf)
.readAllBytes();
// Directly redirect an InputStream to an OutputStream
new ByteArrayInputStream(buf)
.transferTo(System.out);