使用ByteArrayOutputStream内存泄露
今天在对文件进行操作的时候,发现读取20M以上的文件,JVM 就抛出Exception in thread "main" java.lang.OutOfMemoryError: Java heap space,内存溢出,请个老鸟们帮帮忙,如何可以让程序读取比较大的文件。
public class TestString3
{
static final int BUFFER = 2048;
/**
* 写入byte[]文件流数据
* */
public void witeFileData(byte [] data,String zipfilePath)
{
OutputStream out = null;
try
{
out = new FileOutputStream(zipfilePath);
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
try
{
out.write(data);
out.flush();
out.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public byte[] readFileData(String zipfilePath)
{
byte result [] = null;
try
{
ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
InputStream stream = new FileInputStream(zipfilePath);
byte[] tmp = new byte[1024];
// tmp = new byte[stream.available()];
int bytesRead = stream.read(tmp);
while(bytesRead != -1)
{
out.write(tmp, 0, bytesRead);
bytesRead = stream.read(tmp);
}
result = out.toByteArray();
}
catch(Exception ex)
{
ex.printStackTrace();
}
return result;
}
public static void main(String[] args)
{
TestString3 string3 = new TestString3();
byte [] data = string3.readFileData("2222.rar");
string3.witeFileData(data, "E://PLSQL Developer 8.0 .rar");
}
}