Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to manage streams of bytes and when to close the streams
    text
    copied!<p>I'm experiencing java.lang.OutOfMemoryError: Java heap space whenever I try to execute my code. However, if I close my streams in certain instances the error goes away, but because my streams are closing prematurely I'm missing data.</p> <p>I'm very new to Java and I'm clearly not understanding how to manage the streams. How and when should I close streams?</p> <pre><code>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; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload