【发布时间】:2013-02-13 12:22:50
【问题描述】:
每当我尝试执行我的代码时,我都会遇到 java.lang.OutOfMemoryError: Java heap space。但是,如果我在某些情况下关闭流,错误就会消失,但由于我的流过早关闭,我会丢失数据。
我对 Java 很陌生,显然不了解如何管理流。我应该如何以及何时关闭流?
private void handleFile(File source)
{
FileInputStream fis = null;
try
{
if(source.isFile())
{
fis = new FileInputStream(source);
handleFile(source.getAbsolutePath(), fis);
}
else if(source.isDirectory())
{
for(File file:source.listFiles())
{
if(file.isFile())
{
fis = new FileInputStream(file);
handleFile(file, fis);
}
else
{
handleFile(file);
}
}
}
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
finally
{
try
{
if(fis != null) { fis.close(); }
}
catch(IOException ioe) { ioe.printStackTrace(); }
}
}
private handleFile(String fileName, InputStream inputStream)
{
try
{
byte[] initialBytes = isToByteArray(inputStream);
byte[] finalBytes = initialBytes;
if(initialBytes.length == 0) return;
if(isBytesTypeB(initialBytes))
{
finalBytes = getBytesTypeB(startingBytes);
}
// Other similar method checks
// .....
map.put(fileName, finalBytes);
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
private byte[] isToByteArray(InputStream inputStream)
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int nRead;
while((nRead = inputStream.read(buffer)) != -1)
{
baos.write(buffer, 0, nRead);
}
return baos.toByteArray();
}
private boolean isBytesTypeB(byte[] fileBytes)
{
// Checks if these bytes match a particular type
if(BytesMatcher.matches(fileBytes, fileBytes.length))
{
return true;
}
return false;
}
private byte[] getBytesTypeB(byte[] fileBytes)
{
//decompress bytes
return decompressedBytes;
}
【问题讨论】:
-
合并后的文件有多大?
-
不超过 5 - 10 Mb。
-
哦..合并。我不知道。我正在对一个目录运行我的程序,读入每个文件的字节,对这些字节做一些事情,然后将文件名和一个对这些字节做一些事情的对象存储到一个映射中。
-
阅读完毕后,您应该关闭所有流。请注意,当您读取目录中的文件时,流并未关闭。
-
您应该在操作后关闭handleFile函数中的Inputstream fis
标签: java file-io inputstream out-of-memory