java.lang.OutOfMemoryError : 코드를 실행할 때마다 Java 힙 공간이 발생합니다. 그러나 특정 인스턴스에서 스트림을 닫으면 오류가 사라지지만 스트림이 너무 빨리 닫히기 때문에 데이터가 누락됩니다.바이트 스트림을 관리하고 스트림을 닫는 방법
저는 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;
}
파일의 크기는 얼마나됩니까? – Ingo
5 - 10 Mb. –
Ohh .. combined. 나는 잘 모르겠다. 디렉토리에 대해 프로그램을 실행하고, 각 파일의 바이트를 읽고, 그 바이트로 작업 한 다음 fileName과 그 바이트로 이루어진 작업을 맵에 저장합니다. –