From 574a2b51f87bed18a94bc60e311539597be96193 Mon Sep 17 00:00:00 2001 From: bean5 <2052646+bean5@users.noreply.github.com> Date: Fri, 16 Jul 2021 13:39:15 -0600 Subject: [PATCH] Close streams even if catch occurs (avoid memory leaks) --- .../main/java/com/csl/cs108library4a/Utility.java | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/cs108library4a/src/main/java/com/csl/cs108library4a/Utility.java b/cs108library4a/src/main/java/com/csl/cs108library4a/Utility.java index c9f60e3..433e5ed 100644 --- a/cs108library4a/src/main/java/com/csl/cs108library4a/Utility.java +++ b/cs108library4a/src/main/java/com/csl/cs108library4a/Utility.java @@ -133,15 +133,20 @@ void debugFileClose() { } void debugFileEnable(boolean enable) { enableFileDebug = enable; } void writeDebug2File(String stringDebug) { - if (fileDebug != null && enableFileDebug) { + if (fileDebug != null && inventoring) { + FileOutputStream outputStreamDebug; + PrintWriter printWriterDebug; try { - FileOutputStream outputStreamDebug = new FileOutputStream(fileDebug, true); - PrintWriter printWriterDebug = new PrintWriter(new OutputStreamWriter(new BufferedOutputStream(outputStreamDebug), "UTF-8")); + outputStreamDebug = new FileOutputStream(fileDebug, true); + printWriterDebug = new PrintWriter(new OutputStreamWriter(new BufferedOutputStream(outputStreamDebug), "UTF-8")); printWriterDebug.println(stringDebug); - printWriterDebug.flush(); printWriterDebug.close(); - outputStreamDebug.close(); } catch (Exception ex) { } + if(outputStreamDebug != null) outputStreamDebug.close(); + if(printWriterDebug) { + printWriterDebug.flush(); + printWriterDebug.close(); + } } } }