From cd49d29e52d31529811c08a8b6c14abe53d18745 Mon Sep 17 00:00:00 2001 From: Federico Fissore Date: Mon, 4 May 2015 15:44:34 +0200 Subject: [PATCH] Lots of unclosed input and output streams now properly closed. They were preventing Boards Manager from working on Windows --- app/src/processing/app/Base.java | 64 +++++++------- app/src/processing/app/Theme.java | 3 +- app/src/processing/app/UpdateCheck.java | 23 +++-- .../processing/app/syntax/PdeKeywords.java | 83 ++++++++++--------- .../GPGDetachedSignatureVerifier.java | 40 ++++++--- .../libraries/LibrariesIndexer.java | 27 +++--- .../packages/ContributionInstaller.java | 6 +- .../packages/ContributionsIndexer.java | 21 +++-- .../cc/arduino/utils/ArchiveExtractor.java | 21 ++--- .../src/cc/arduino/utils/FileHash.java | 17 ++-- .../src/processing/app/BaseNoGui.java | 15 ++-- .../src/processing/app/PreferencesData.java | 63 ++++---------- .../src/processing/app/debug/Compiler.java | 12 ++- .../app/helpers/PreferencesMap.java | 20 +++-- .../src/processing/app/legacy/PApplet.java | 38 +++++++-- 15 files changed, 252 insertions(+), 201 deletions(-) diff --git a/app/src/processing/app/Base.java b/app/src/processing/app/Base.java index 7db2bd2cd..965b37ba6 100644 --- a/app/src/processing/app/Base.java +++ b/app/src/processing/app/Base.java @@ -2406,14 +2406,6 @@ public class Base { } - /** - * Return an InputStream for a file inside the Processing lib folder. - */ - static public InputStream getLibStream(String filename) throws IOException { - return BaseNoGui.getLibStream(filename); - } - - // ................................................................... @@ -2431,17 +2423,22 @@ public class Base { */ static public byte[] loadBytesRaw(File file) throws IOException { int size = (int) file.length(); - FileInputStream input = new FileInputStream(file); - byte buffer[] = new byte[size]; - int offset = 0; - int bytesRead; - while ((bytesRead = input.read(buffer, offset, size - offset)) != -1) { - offset += bytesRead; - if (bytesRead == 0) break; + FileInputStream input = null; + try { + input = new FileInputStream(file); + byte buffer[] = new byte[size]; + int offset = 0; + int bytesRead; + while ((bytesRead = input.read(buffer, offset, size - offset)) != -1) { + offset += bytesRead; + if (bytesRead == 0) break; + } + return buffer; + } finally { + if (input != null) { + input.close(); + } } - input.close(); // weren't properly being closed - input = null; - return buffer; } @@ -2476,20 +2473,25 @@ public class Base { static public void copyFile(File sourceFile, File targetFile) throws IOException { - InputStream from = - new BufferedInputStream(new FileInputStream(sourceFile)); - OutputStream to = - new BufferedOutputStream(new FileOutputStream(targetFile)); - byte[] buffer = new byte[16 * 1024]; - int bytesRead; - while ((bytesRead = from.read(buffer)) != -1) { - to.write(buffer, 0, bytesRead); + InputStream from = null; + OutputStream to = null; + try { + from = new BufferedInputStream(new FileInputStream(sourceFile)); + to = new BufferedOutputStream(new FileOutputStream(targetFile)); + byte[] buffer = new byte[16 * 1024]; + int bytesRead; + while ((bytesRead = from.read(buffer)) != -1) { + to.write(buffer, 0, bytesRead); + } + to.flush(); + } finally { + if (from != null) { + from.close(); // ?? + } + if (to != null) { + to.close(); // ?? + } } - to.flush(); - from.close(); // ?? - from = null; - to.close(); // ?? - to = null; targetFile.setLastModified(sourceFile.lastModified()); } diff --git a/app/src/processing/app/Theme.java b/app/src/processing/app/Theme.java index 7f23d3c46..4100bdfc5 100644 --- a/app/src/processing/app/Theme.java +++ b/app/src/processing/app/Theme.java @@ -26,6 +26,7 @@ import static processing.app.I18n._; import java.awt.Color; import java.awt.Font; import java.awt.SystemColor; +import java.io.File; import processing.app.helpers.PreferencesHelper; import processing.app.helpers.PreferencesMap; @@ -45,7 +46,7 @@ public class Theme { static protected void init() { try { - table.load(Base.getLibStream("theme/theme.txt")); + table.load(new File(BaseNoGui.getContentFile("lib"), "theme/theme.txt")); } catch (Exception te) { Base.showError(null, _("Could not read color theme settings.\n" + "You'll need to reinstall Arduino."), te); diff --git a/app/src/processing/app/UpdateCheck.java b/app/src/processing/app/UpdateCheck.java index 5e063bc6c..ac8117cb2 100644 --- a/app/src/processing/app/UpdateCheck.java +++ b/app/src/processing/app/UpdateCheck.java @@ -22,16 +22,16 @@ package processing.app; +import processing.app.legacy.PApplet; + +import javax.swing.*; import java.io.BufferedReader; -import java.io.InputStream; +import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.net.URLEncoder; import java.util.Random; -import javax.swing.JOptionPane; - -import processing.app.legacy.PApplet; import static processing.app.I18n._; @@ -126,11 +126,16 @@ public class UpdateCheck implements Runnable { } - protected int readInt(String filename) throws Exception { + protected int readInt(String filename) throws IOException { URL url = new URL(filename); - InputStream stream = url.openStream(); - InputStreamReader isr = new InputStreamReader(stream); - BufferedReader reader = new BufferedReader(isr); - return Integer.parseInt(reader.readLine()); + BufferedReader reader = null; + try { + reader = new BufferedReader(new InputStreamReader(url.openStream())); + return Integer.parseInt(reader.readLine()); + } finally { + if (reader != null) { + reader.close(); + } + } } } diff --git a/app/src/processing/app/syntax/PdeKeywords.java b/app/src/processing/app/syntax/PdeKeywords.java index 865325da3..b221796a5 100644 --- a/app/src/processing/app/syntax/PdeKeywords.java +++ b/app/src/processing/app/syntax/PdeKeywords.java @@ -61,10 +61,10 @@ public class PdeKeywords extends CTokenMarker { try { keywordColoring = new KeywordMap(false); keywordToReference = new Hashtable(); - getKeywords(Base.getLibStream("keywords.txt")); + getKeywords(new File(BaseNoGui.getContentFile("lib"), "keywords.txt")); for (ContributedLibrary lib : Base.getLibraries()) { File keywords = new File(lib.getInstalledFolder(), "keywords.txt"); - if (keywords.exists()) getKeywords(new FileInputStream(keywords)); + if (keywords.exists()) getKeywords(keywords); } } catch (Exception e) { Base.showError("Problem loading keywords", @@ -76,51 +76,56 @@ public class PdeKeywords extends CTokenMarker { return keywordColoring; } - static private void getKeywords(InputStream input) throws Exception { - InputStreamReader isr = new InputStreamReader(input); - BufferedReader reader = new BufferedReader(isr); + static private void getKeywords(File input) throws IOException { + BufferedReader reader = null; + try { + reader = new BufferedReader(new InputStreamReader(new FileInputStream(input))); - String line = null; - while ((line = reader.readLine()) != null) { - //System.out.println("line is " + line); - // in case there's any garbage on the line - //if (line.trim().length() == 0) continue; + String line = null; + while ((line = reader.readLine()) != null) { + //System.out.println("line is " + line); + // in case there's any garbage on the line + //if (line.trim().length() == 0) continue; - String pieces[] = PApplet.split(line, '\t'); - if (pieces.length >= 2) { - //int tab = line.indexOf('\t'); - // any line with no tab is ignored - // meaning that a comment is any line without a tab - //if (tab == -1) continue; + String pieces[] = PApplet.split(line, '\t'); + if (pieces.length >= 2) { + //int tab = line.indexOf('\t'); + // any line with no tab is ignored + // meaning that a comment is any line without a tab + //if (tab == -1) continue; - String keyword = pieces[0].trim(); - //String keyword = line.substring(0, tab).trim(); - //String second = line.substring(tab + 1); - //tab = second.indexOf('\t'); - //String coloring = second.substring(0, tab).trim(); - //String htmlFilename = second.substring(tab + 1).trim(); - String coloring = pieces[1].trim(); + String keyword = pieces[0].trim(); + //String keyword = line.substring(0, tab).trim(); + //String second = line.substring(tab + 1); + //tab = second.indexOf('\t'); + //String coloring = second.substring(0, tab).trim(); + //String htmlFilename = second.substring(tab + 1).trim(); + String coloring = pieces[1].trim(); - if (coloring.length() > 0 && Character.isDigit(coloring.charAt(coloring.length() - 1))) { - // text will be KEYWORD or LITERAL - boolean isKey = (coloring.charAt(0) == 'K'); - // KEYWORD1 -> 0, KEYWORD2 -> 1, etc - int num = coloring.charAt(coloring.length() - 1) - '1'; - byte id = (byte) - ((isKey ? Token.KEYWORD1 : Token.LITERAL1) + num); - //System.out.println("got " + (isKey ? "keyword" : "literal") + - // (num+1) + " for " + keyword); - keywordColoring.add(keyword, id); - } - if (pieces.length >= 3) { - String htmlFilename = pieces[2].trim(); - if (htmlFilename.length() > 0) { - keywordToReference.put(keyword, htmlFilename); + if (coloring.length() > 0 && Character.isDigit(coloring.charAt(coloring.length() - 1))) { + // text will be KEYWORD or LITERAL + boolean isKey = (coloring.charAt(0) == 'K'); + // KEYWORD1 -> 0, KEYWORD2 -> 1, etc + int num = coloring.charAt(coloring.length() - 1) - '1'; + byte id = (byte) + ((isKey ? Token.KEYWORD1 : Token.LITERAL1) + num); + //System.out.println("got " + (isKey ? "keyword" : "literal") + + // (num+1) + " for " + keyword); + keywordColoring.add(keyword, id); + } + if (pieces.length >= 3) { + String htmlFilename = pieces[2].trim(); + if (htmlFilename.length() > 0) { + keywordToReference.put(keyword, htmlFilename); + } } } } + } finally { + if (reader != null) { + reader.close(); + } } - reader.close(); } diff --git a/arduino-core/src/cc/arduino/contributions/GPGDetachedSignatureVerifier.java b/arduino-core/src/cc/arduino/contributions/GPGDetachedSignatureVerifier.java index 718cd3080..cd64d59e6 100644 --- a/arduino-core/src/cc/arduino/contributions/GPGDetachedSignatureVerifier.java +++ b/arduino-core/src/cc/arduino/contributions/GPGDetachedSignatureVerifier.java @@ -52,23 +52,41 @@ public class GPGDetachedSignatureVerifier { public boolean verify(File signedFile, File signature, File publicKey) throws IOException, PGPException { PGPPublicKey pgpPublicKey = readPublicKey(publicKey, keyId); - PGPObjectFactory pgpObjectFactory = new PGPObjectFactory(new FileInputStream(signature), new BcKeyFingerprintCalculator()); + FileInputStream signatureInputStream = null; + FileInputStream signedFileInputStream = null; + try { + signatureInputStream = new FileInputStream(signature); + PGPObjectFactory pgpObjectFactory = new PGPObjectFactory(signatureInputStream, new BcKeyFingerprintCalculator()); - PGPSignatureList pgpSignatureList = (PGPSignatureList) pgpObjectFactory.nextObject(); - assert pgpSignatureList.size() == 1; - PGPSignature pgpSignature = pgpSignatureList.get(0); + PGPSignatureList pgpSignatureList = (PGPSignatureList) pgpObjectFactory.nextObject(); + assert pgpSignatureList.size() == 1; + PGPSignature pgpSignature = pgpSignatureList.get(0); - pgpSignature.init(new BcPGPContentVerifierBuilderProvider(), pgpPublicKey); - pgpSignature.update(IOUtils.toByteArray(new FileInputStream(signedFile))); + pgpSignature.init(new BcPGPContentVerifierBuilderProvider(), pgpPublicKey); + signedFileInputStream = new FileInputStream(signedFile); + pgpSignature.update(IOUtils.toByteArray(signedFileInputStream)); - return pgpSignature.verify(); + return pgpSignature.verify(); + } finally { + if (signatureInputStream != null) { + signatureInputStream.close(); + } + if (signedFileInputStream != null) { + signedFileInputStream.close(); + } + } } private PGPPublicKey readPublicKey(File file, String keyId) throws IOException, PGPException { - InputStream keyIn = new BufferedInputStream(new FileInputStream(file)); - PGPPublicKey pubKey = readPublicKey(keyIn, keyId); - keyIn.close(); - return pubKey; + InputStream keyIn = null; + try { + keyIn = new BufferedInputStream(new FileInputStream(file)); + return readPublicKey(keyIn, keyId); + } finally { + if (keyIn != null) { + keyIn.close(); + } + } } private PGPPublicKey readPublicKey(InputStream input, String keyId) throws IOException, PGPException { diff --git a/arduino-core/src/cc/arduino/contributions/libraries/LibrariesIndexer.java b/arduino-core/src/cc/arduino/contributions/libraries/LibrariesIndexer.java index 7493d0e08..c285ade68 100644 --- a/arduino-core/src/cc/arduino/contributions/libraries/LibrariesIndexer.java +++ b/arduino-core/src/cc/arduino/contributions/libraries/LibrariesIndexer.java @@ -70,17 +70,24 @@ public class LibrariesIndexer { } private void parseIndex(File indexFile) throws IOException { - InputStream indexIn = new FileInputStream(indexFile); - ObjectMapper mapper = new ObjectMapper(); - mapper.registerModule(new MrBeanModule()); - mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); - mapper.configure(DeserializationFeature.EAGER_DESERIALIZER_FETCH, true); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - index = mapper.readValue(indexIn, LibrariesIndex.class); + InputStream indexIn = null; + try { + indexIn = new FileInputStream(indexFile); + ObjectMapper mapper = new ObjectMapper(); + mapper.registerModule(new MrBeanModule()); + mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); + mapper.configure(DeserializationFeature.EAGER_DESERIALIZER_FETCH, true); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + index = mapper.readValue(indexIn, LibrariesIndex.class); - for (ContributedLibrary library : index.getLibraries()) { - if (library.getCategory() == null || "".equals(library.getCategory())) { - library.setCategory("Uncategorized"); + for (ContributedLibrary library : index.getLibraries()) { + if (library.getCategory() == null || "".equals(library.getCategory())) { + library.setCategory("Uncategorized"); + } + } + } finally { + if (indexIn != null) { + indexIn.close(); } } } diff --git a/arduino-core/src/cc/arduino/contributions/packages/ContributionInstaller.java b/arduino-core/src/cc/arduino/contributions/packages/ContributionInstaller.java index a9ae55db5..4abd4801a 100644 --- a/arduino-core/src/cc/arduino/contributions/packages/ContributionInstaller.java +++ b/arduino-core/src/cc/arduino/contributions/packages/ContributionInstaller.java @@ -277,10 +277,12 @@ public class ContributionInstaller { // Replace old index with the updated one if (outputFile.exists()) { - outputFile.delete(); + if (!outputFile.delete()) { + throw new Exception("An error occurred while updating platforms index! I can't delete file " + outputFile); + } } if (!tmpFile.renameTo(outputFile)) { - throw new Exception("An error occurred while updating platforms index!"); + throw new Exception("An error occurred while updating platforms index! I can't rename file " + tmpFile); } return outputFile; diff --git a/arduino-core/src/cc/arduino/contributions/packages/ContributionsIndexer.java b/arduino-core/src/cc/arduino/contributions/packages/ContributionsIndexer.java index 4f1bff48c..fd26b7e68 100644 --- a/arduino-core/src/cc/arduino/contributions/packages/ContributionsIndexer.java +++ b/arduino-core/src/cc/arduino/contributions/packages/ContributionsIndexer.java @@ -158,13 +158,20 @@ public class ContributionsIndexer { } private ContributionsIndex parseIndex(File indexFile) throws IOException { - InputStream indexIn = new FileInputStream(indexFile); - ObjectMapper mapper = new ObjectMapper(); - mapper.registerModule(new MrBeanModule()); - mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); - mapper.configure(DeserializationFeature.EAGER_DESERIALIZER_FETCH, true); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - return mapper.readValue(indexIn, ContributionsIndex.class); + InputStream inputStream = null; + try { + inputStream = new FileInputStream(indexFile); + ObjectMapper mapper = new ObjectMapper(); + mapper.registerModule(new MrBeanModule()); + mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); + mapper.configure(DeserializationFeature.EAGER_DESERIALIZER_FETCH, true); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + return mapper.readValue(inputStream, ContributionsIndex.class); + } finally { + if (inputStream != null) { + inputStream.close(); + } + } } public void syncWithFilesystem(File hardwareFolder) throws IOException { diff --git a/arduino-core/src/cc/arduino/utils/ArchiveExtractor.java b/arduino-core/src/cc/arduino/utils/ArchiveExtractor.java index 8e4ed800d..fe68fa870 100644 --- a/arduino-core/src/cc/arduino/utils/ArchiveExtractor.java +++ b/arduino-core/src/cc/arduino/utils/ArchiveExtractor.java @@ -91,19 +91,13 @@ public class ArchiveExtractor { // Create an ArchiveInputStream with the correct archiving algorithm if (archiveFile.getName().endsWith("tar.bz2")) { - InputStream fin = new FileInputStream(archiveFile); - fin = new BZip2CompressorInputStream(fin); - in = new TarArchiveInputStream(fin); + in = new TarArchiveInputStream(new BZip2CompressorInputStream(new FileInputStream(archiveFile))); } else if (archiveFile.getName().endsWith("zip")) { - InputStream fin = new FileInputStream(archiveFile); - in = new ZipArchiveInputStream(fin); + in = new ZipArchiveInputStream(new FileInputStream(archiveFile)); } else if (archiveFile.getName().endsWith("tar.gz")) { - InputStream fin = new FileInputStream(archiveFile); - fin = new GzipCompressorInputStream(fin); - in = new TarArchiveInputStream(fin); + in = new TarArchiveInputStream(new GzipCompressorInputStream(new FileInputStream(archiveFile))); } else if (archiveFile.getName().endsWith("tar")) { - InputStream fin = new FileInputStream(archiveFile); - in = new TarArchiveInputStream(fin); + in = new TarArchiveInputStream(new FileInputStream(archiveFile)); } else { throw new IOException("Archive format not supported."); } @@ -276,8 +270,9 @@ public class ArchiveExtractor { } private static void copyStreamToFile(InputStream in, long size, File outputFile) throws IOException { - FileOutputStream fos = new FileOutputStream(outputFile); + FileOutputStream fos = null; try { + fos = new FileOutputStream(outputFile); // if size is not available, copy until EOF... if (size == -1) { byte buffer[] = new byte[4096]; @@ -299,7 +294,9 @@ public class ArchiveExtractor { size -= length; } } finally { - fos.close(); + if (fos != null) { + fos.close(); + } } } diff --git a/arduino-core/src/cc/arduino/utils/FileHash.java b/arduino-core/src/cc/arduino/utils/FileHash.java index 87dabe172..0ce8afd4c 100644 --- a/arduino-core/src/cc/arduino/utils/FileHash.java +++ b/arduino-core/src/cc/arduino/utils/FileHash.java @@ -40,19 +40,18 @@ public class FileHash { * Calculate a message digest of a file using the algorithm specified. The * result is a string containing the algorithm name followed by ":" and by the * resulting hash in hex. - * + * * @param file - * @param algorithm - * For example "SHA-256" + * @param algorithm For example "SHA-256" * @return The algorithm followed by ":" and the hash, for example:
- * "SHA-256:ee6796513086080cca078cbb383f543c5e508b647a71c9d6f39b7bca41071883" + * "SHA-256:ee6796513086080cca078cbb383f543c5e508b647a71c9d6f39b7bca41071883" * @throws IOException * @throws NoSuchAlgorithmException */ - public static String hash(File file, String algorithm) throws IOException, - NoSuchAlgorithmException { - FileInputStream in = new FileInputStream(file); + public static String hash(File file, String algorithm) throws IOException, NoSuchAlgorithmException { + FileInputStream in = null; try { + in = new FileInputStream(file); byte buff[] = new byte[10240]; MessageDigest digest = MessageDigest.getInstance(algorithm); while (in.available() > 0) { @@ -69,7 +68,9 @@ public class FileHash { } return algorithm + ":" + res; } finally { - in.close(); + if (in != null) { + in.close(); + } } } } diff --git a/arduino-core/src/processing/app/BaseNoGui.java b/arduino-core/src/processing/app/BaseNoGui.java index 01adce511..06e807fbe 100644 --- a/arduino-core/src/processing/app/BaseNoGui.java +++ b/arduino-core/src/processing/app/BaseNoGui.java @@ -233,13 +233,6 @@ public class BaseNoGui { return librariesFolders; } - /** - * Return an InputStream for a file inside the Processing lib folder. - */ - static public InputStream getLibStream(String filename) throws IOException { - return new FileInputStream(new File(getContentFile("lib"), filename)); - } - static public Platform getPlatform() { return platform; } @@ -624,13 +617,17 @@ public class BaseNoGui { if (defaultLibraryJsonFile.isFile()) { FileUtils.copyFile(defaultLibraryJsonFile, librariesIndexFile); } else { + FileOutputStream out = null; try { // Otherwise create an empty packages index - FileOutputStream out = new FileOutputStream(librariesIndexFile); + out = new FileOutputStream(librariesIndexFile); out.write("{ \"libraries\" : [ ] }".getBytes()); - out.close(); } catch (IOException e) { e.printStackTrace(); + } finally { + if (out != null) { + out.close(); + } } } } diff --git a/arduino-core/src/processing/app/PreferencesData.java b/arduino-core/src/processing/app/PreferencesData.java index b34629983..d6dc14679 100644 --- a/arduino-core/src/processing/app/PreferencesData.java +++ b/arduino-core/src/processing/app/PreferencesData.java @@ -45,7 +45,7 @@ public class PreferencesData { // start by loading the defaults, in case something // important was deleted from the user prefs try { - prefs.load(BaseNoGui.getLibStream(PREFS_FILE)); + prefs.load(new File(BaseNoGui.getContentFile("lib"), PREFS_FILE)); } catch (IOException e) { BaseNoGui.showError(null, _("Could not read default settings.\n" + "You'll need to reinstall Arduino."), e); @@ -94,41 +94,6 @@ public class PreferencesData { } - static public String[] loadStrings(InputStream input) { - try { - BufferedReader reader = - new BufferedReader(new InputStreamReader(input, "UTF-8")); - - String lines[] = new String[100]; - int lineCount = 0; - String line = null; - while ((line = reader.readLine()) != null) { - if (lineCount == lines.length) { - String temp[] = new String[lineCount << 1]; - System.arraycopy(lines, 0, temp, 0, lineCount); - lines = temp; - } - lines[lineCount++] = line; - } - reader.close(); - - if (lineCount == lines.length) { - return lines; - } - - // resize array to appropriate amount for these lines - String output[] = new String[lineCount]; - System.arraycopy(lines, 0, output, 0, lineCount); - return output; - - } catch (IOException e) { - e.printStackTrace(); - //throw new RuntimeException("Error inside loadStrings()"); - } - return null; - } - - static protected void save() { if (!doSave) return; @@ -139,19 +104,25 @@ public class PreferencesData { if (preferencesFile == null) return; // Fix for 0163 to properly use Unicode when writing preferences.txt - PrintWriter writer = PApplet.createWriter(preferencesFile); + PrintWriter writer = null; + try { + writer = PApplet.createWriter(preferencesFile); - String[] keys = prefs.keySet().toArray(new String[0]); - Arrays.sort(keys); - for (String key: keys) { - if (key.startsWith("runtime.")) - continue; - writer.println(key + "=" + prefs.get(key)); + String[] keys = prefs.keySet().toArray(new String[0]); + Arrays.sort(keys); + for (String key : keys) { + if (key.startsWith("runtime.")) + continue; + writer.println(key + "=" + prefs.get(key)); + } + + writer.flush(); + } finally { + if (writer != null) { + writer.close(); + } } - writer.flush(); - writer.close(); - try { BaseNoGui.getPlatform().fixPrefsFilePermissions(preferencesFile); } catch (Exception e) { diff --git a/arduino-core/src/processing/app/debug/Compiler.java b/arduino-core/src/processing/app/debug/Compiler.java index e1c2e2fb2..1bc0f9074 100644 --- a/arduino-core/src/processing/app/debug/Compiler.java +++ b/arduino-core/src/processing/app/debug/Compiler.java @@ -1210,12 +1210,12 @@ public class Compiler implements MessageConsumer { // 2. run preproc on that code using the sugg class name // to create a single .java file and write to buildpath + FileOutputStream outputStream = null; try { // Output file File streamFile = new File(buildPath, sketch.getName() + ".cpp"); - FileOutputStream outputStream = new FileOutputStream(streamFile); + outputStream = new FileOutputStream(streamFile); preprocessor.write(outputStream); - outputStream.close(); } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(); String msg = _("Build folder disappeared or could not be written"); @@ -1230,6 +1230,14 @@ public class Compiler implements MessageConsumer { System.err.println(I18n.format(_("Uncaught exception type: {0}"), ex.getClass())); ex.printStackTrace(); throw new RunnerException(ex.toString()); + } finally { + if (outputStream != null) { + try { + outputStream.close(); + } catch (IOException e) { + //noop + } + } } // grab the imports from the code just preproc'd diff --git a/arduino-core/src/processing/app/helpers/PreferencesMap.java b/arduino-core/src/processing/app/helpers/PreferencesMap.java index f26c2b122..185e1bee4 100644 --- a/arduino-core/src/processing/app/helpers/PreferencesMap.java +++ b/arduino-core/src/processing/app/helpers/PreferencesMap.java @@ -21,18 +21,14 @@ */ package processing.app.helpers; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; +import processing.app.legacy.PApplet; + +import java.io.*; import java.util.LinkedHashMap; import java.util.Map; import java.util.SortedSet; import java.util.TreeSet; -import processing.app.legacy.PApplet; - @SuppressWarnings("serial") public class PreferencesMap extends LinkedHashMap { @@ -71,7 +67,15 @@ public class PreferencesMap extends LinkedHashMap { * @throws IOException */ public void load(File file) throws IOException { - load(new FileInputStream(file)); + FileInputStream fileInputStream = null; + try { + fileInputStream = new FileInputStream(file); + load(fileInputStream); + } finally { + if (fileInputStream != null) { + fileInputStream.close(); + } + } } protected String processPlatformSuffix(String key, String suffix, boolean isCurrentPlatform) { diff --git a/arduino-core/src/processing/app/legacy/PApplet.java b/arduino-core/src/processing/app/legacy/PApplet.java index 59ca701e3..e89955263 100644 --- a/arduino-core/src/processing/app/legacy/PApplet.java +++ b/arduino-core/src/processing/app/legacy/PApplet.java @@ -266,9 +266,20 @@ public class PApplet { } static public String[] loadStrings(File file) { - InputStream is = createInput(file); - if (is != null) return loadStrings(is); - return null; + InputStream is = null; + try { + is = createInput(file); + if (is != null) return loadStrings(is); + return null; + } finally { + if (is != null) { + try { + is.close(); + } catch (IOException e) { + // noop + } + } + } } static public String[] loadStrings(InputStream input) { @@ -319,14 +330,29 @@ public class PApplet { static public void saveStrings(File file, String strings[]) { - saveStrings(createOutput(file), strings); + OutputStream outputStream = null; + try { + outputStream = createOutput(file); + saveStrings(outputStream, strings); + } finally { + if (outputStream != null) { + try { + outputStream.close(); + } catch (IOException e) { + //noop + } + } + } } static public void saveStrings(OutputStream output, String strings[]) { PrintWriter writer = createWriter(output); - for (int i = 0; i < strings.length; i++) { - writer.println(strings[i]); + if (writer == null) { + return; + } + for (String string : strings) { + writer.println(string); } writer.flush(); writer.close();