要避免从流和读写器中产生内存泄漏,需要遵循以下几个步骤:
try (InputStream inputStream = new FileInputStream("file.txt")) { // do something with the input stream } catch (IOException e) { // handle exception }
InputStream inputStream = null; try { inputStream = new FileInputStream("file.txt"); // do something with the input stream } catch (IOException e) { // handle exception } finally { try { if (inputStream != null) { inputStream.close(); } } catch (IOException e) { // handle exception } }
BufferedWriter writer = null; try { writer = new BufferedWriter(new FileWriter("file.txt")); // do something with the writer writer.flush(); } catch (IOException e) { // handle exception } finally { try { if (writer != null) { writer.close(); } } catch (IOException e) { // handle exception } }
遵循这些步骤可以有效地避免从流和读写器中产生内存泄漏。
上一篇:避免ListView重新构建
下一篇:避免浏览器弹窗