【问题标题】:File(s) and InputStream/OutputStream文件和 InputStream/OutputStream
【发布时间】:2012-08-03 22:22:22
【问题描述】:

你好 Stack Overflow 社区,

我正在对使用 java Servlet 接收的一些数据进行多步处理。我目前的过程是我使用 Apache File Upload 将文件输入到服务器并将它们转换为File。然后,一旦input1 填充了数据,我就会运行类似于此的流程(其中流程函数是 xsl 转换):

File input1 = new File(FILE_NAME);  // <---this is populated with data
File output1 = new File(TEMP_FILE); // <---this is the temporary file

InputStream read = new FileInputStream(input1); 
OuputStream out = new FileOutputStream(output1);

process1ThatReadsProcessesOutputs( read, out);

out.close();
read.close();

//this is basically a repeat of the above process!
File output2 = new File(RESULT_FILE);  // <--- This is the result file 
InputStream read1 = new FileInputStream(output1);
OutputStream out1 = new FileOutputStream(output2);
Process2ThatReadsProcessesOutputs( read1, out1);
read1.close();
out1.close();
…

所以我的问题是,是否有更好的方法来做到这一点,这样我就不必创建那些临时的 Files 并重新创建流到那些 Files 的流? (我假设我的表现不错)

我看到了这个Most Efficient Way to create InputStream from OutputStream,但我不确定这是否是最好的路线......

【问题讨论】:

    标签: java


    【解决方案1】:

    只需将FileOutputStream 替换为ByteArrayInputStream,反之亦然。

    例子:

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
    

    【讨论】:

    • 我查看了 BufferedStream 上的文档...这一行 InputStream read1 = new FileInputStream(out); 是否使用 FileInputStream(FileDescriptor fdObj) 构造函数?
    【解决方案2】:

    我不知道你为什么要转换使用 Apache Commons 检索到的 FileItem,如果你真的不需要的话。您可以使用每个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();
    

    所以最后,您可以使用InputStream 对象来读取客户端发送的上传流,避免不必要的实例化。

    是的,确实建议使用像BufferedInputStreamBufferedOutputStream 这样的缓冲类。

    如果您不需要写入磁盘(总是比在内存中工作慢),另一种想法可能是避免使用FileOutputStream(中间那个)并将其替换为ByteArrayOutputStream

    【讨论】:

      【解决方案3】:

      Java 9 为这个问题带来了新的答案:

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

      【讨论】:

        猜你喜欢
        • 2011-08-13
        • 2011-08-25
        • 2018-02-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-06
        相关资源
        最近更新 更多