前一段時間,我在尋求下面的代碼的幫助,並最終開始再次處理它。基本上,我已經收窄我的錯誤下來的文件導致此錯誤大小:從Java中的大文件中讀取字節會導致Java堆空間錯誤
異常線程「main」 java.lang.OutOfMemoryError:Java堆空間
正下方的錯誤行在堆棧跟蹤是: 在java.util.Arrays.copyOf(Arrays.java:2786)
我可以通過這個程序有成千上萬的小文件大的目錄,但在這50 MB大小的任何文件往往會崩潰。我沒有跟蹤程序崩潰的確切大小,但我知道至少有一個50 MB的文件會導致問題。
下面是主要代碼片段,其中堆棧跟蹤告訴我我的代碼正在破壞。
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)
{
byte[] startingBytes = null;
try
{
startingBytes = inputStreamToByteArray(inputStream);
if(startingBytes.length == 0) return;
if(isBytesTypeB(startingBytes))
{
do stuff
return;
}
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
private byte[] inputStreamToByteArray(InputStream inputStream)
{
BufferedInputStream bis = null;
ByteArrayOutputStream baos = null;
try
{
bis = new BufferedInputStream(inputStream);
baos = new ByteArrayOutputStream(bis);
byte[] buffer = new byte[1024];
int nRead;
while((nRead = bis.read(buffer)) != -1)
{
baos.write(buffer, 0, nRead);
}
}
finally { baos.close(); }
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;
}
所以在上面的代碼中有一些導致錯誤。任何想法我在這裏做錯了嗎?
一種解決方法在運行應用程序時會增加堆內存。但是,如果你只是複製一個文件,爲什麼你必須將整個文件保存在RAM中? – 2013-05-08 17:37:34
我的程序需要RAM中的文件,因爲它最終會對讀取的字節做些什麼。 – 2013-05-08 17:38:56
爲什麼不只是將它們處理成塊?如果你指定了真正的問題,你可以得到一個真正的答案,而不是解決方法。 – 2013-05-08 17:39:29