ByteArrayInputStream之内存溢出(IoUtils)

今天一同事做了批量导入数据的功能,但是服务器老是死机。查看服务器内存8G的内存占了7G多,很明显是内存泄漏。后来发现对文件的操作的时候用到了ByteArrayInputStream,仔细查看代码看到了ByteArrayInputStream并没有释放,问题差不多就是这个了,然后想着关闭流,自然的想到了ByteArrayInputStream.close()方法。后经网络查证,close方法在ByteArrayInputStream声明的是空的,原来ByteArrayInputStream是基于内存Byte数组的流,不需要close,当没有强引用的时候会自动被垃圾回收了,所以close实现为空。而后想办法关掉流,用到了org.apache.commons.io.IoUtils工具类。

引用网上的介绍:

该类为input/output操作提供了通用静态方法,可以无条件的关闭任何流。

包括功能:

•closeQuietly——这些关闭一个流的方法将忽略nulls和例外的情况。

•toXxx/read-这些方法从一个流读取数据。

• write这些方法将数据写到一个流里。

copy——这些方法用于从一个流的所有的数据复制到另一个流。

•contentEquals——这些方法用于比较两个流的内容。

下面是一个关闭的实例(红色的部分):

package org.test.toolkit.file;

import java.io.ByteArrayInputStream;

import java.io.ByteArrayOutputStream;

import java.io.IOException;

import org.apache.commons.io.IOUtils;

import org.apache.poi.poifs.filesystem.DirectoryEntry;

import org.apache.poi.poifs.filesystem.POIFSFileSystem;

public class DocFile extends RandomFile {
public static final String EXTENSION = FileType.DOC.toString();

private static final String WORD_TYPE = "WordDocument";

private static byte[] getContentBytes() {
byte byteArray[] = FileUtil.getRandomBytes();

ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArray);

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

try {
POIFSFileSystem fs = new POIFSFileSystem();

DirectoryEntry directory = fs.getRoot();

directory.createDocument(WORD_TYPE, byteArrayInputStream);

fs.writeFilesystem(byteArrayOutputStream);

return byteArrayOutputStream.toByteArray();

} catch (IOException e) {
throw new RandomFileException("create doc file content fail", e);

} finally {
IOUtils.closeQuietly(byteArrayInputStream);

IOUtils.closeQuietly(byteArrayOutputStream);

}

}

public DocFile() {
super(EXTENSION, getContentBytes());

}

}


————————————————
版权声明:本文为CSDN博主「youyedemeng」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/youyedemeng/article/details/21740093

原文地址:https://www.cnblogs.com/javalinux/p/15696255.html