关闭ByteArrayOutputStream的最佳方法是什么?

时间:2012-04-10 19:46:11

标签: java memory stream heap bytearrayoutputstream

我需要优化使用过多堆内存的应用程序。 我在使用相同的文件后关闭ByteArrayOutputStream变量时遇到问题。我尝试使用close()但它不起作用。这是代码:

ByteArrayOutputStream zipOutTempStream = new ByteArrayOutputStream();
//arquivo.getZipStream() has the XML received by FTP.
//STreamEtils is the function who transfers the XML to zipOutTempStream
StreamUtils.copiarStream(arquivo.getZipStream(), zipOutTempStream);

            //Creating a new XML to write over this.
            File arquivo1 = new File("C:/XML.xml");
            if (arquivo1.exists()) {
                System.out.println("ele existe");
            } else {
                if (arquivo1.createNewFile()) {
                    System.out.println("arquivo criado");
                } else {
                    System.out.println("arquivo não criado");
                }
            }

            FileOutputStream arquivo2 = new FileOutputStream(arquivo1);
            //Copy the unziped XML to the new xml created.
            StreamUtils.copiarStream(StreamUtils                .uncompressXmlFromZipStream(new ByteArrayInputStream(zipOutTempStream.toByteArray())), arquivo2);
            arquivo.setZipStream(null);
            arquivo.setXmlStream(null)      
return arquivo;

2 个答案:

答案 0 :(得分:9)

您无法关闭ByteArrayOutputStream,因为它的close()方法记录为

  

关闭ByteArrayOutputStream无效。这个方法   在没有关闭流之后可以调用class   生成IOException。

此输出流由数组支持;它是 NOT 缓冲流。如果您觉得使用了太多内存,则应使用适当的OutputStream将字节直接输出到某个端点,例如文件或套接字。

答案 1 :(得分:3)

我认为你不小心使用了太多的记忆。 close()与此无关。事实上,没有必要关闭ByteArrayOutputStream。在这里,您将ZIP文件复制到包裹的byte[]数组中:

ByteArrayOutputStream zipOutTempStream = new ByteArrayOutputStream();
StreamUtils.copiarStream(arquivo.getZipStream(), zipOutTempStream);

以后几行将byte[]数组转换回InputStream

StreamUtils.copiarStream(StreamUtils.uncompressXmlFromZipStream(
  new ByteArrayInputStream(zipOutTempStream.toByteArray())
), arquivo2);

看起来这样生成的byte[]数组非常大(用日志记录确认)。而不是将整个ZIP文件存储在内存中(在byte[]中)存储在临时文件中并将其读回。

相关问题