From 290b9946f251e2e140790cde6bb0a5dc66878bcb Mon Sep 17 00:00:00 2001 From: Colin Alworth Date: Wed, 6 Nov 2024 10:53:16 -0600 Subject: [PATCH] Close writers, usually with try-with-resources --- .../linker/impl/StandardLinkerContext.java | 9 +- .../core/ext/soyc/coderef/EntityRecorder.java | 9 +- .../ext/soyc/impl/DependencyRecorder.java | 6 +- .../ext/soyc/impl/SplitPointRecorder.java | 101 +++++++++--------- .../gwt/core/ext/soyc/impl/StoryRecorder.java | 3 +- .../gwt/dev/MinimalRebuildCacheManager.java | 14 +-- .../src/com/google/gwt/dev/ServletWriter.java | 32 +++--- .../gwt/dev/javac/PersistentUnitCacheDir.java | 21 +++- .../dev/javac/StandardGeneratorContext.java | 7 +- .../google/gwt/dev/shell/BrowserChannel.java | 15 ++- .../src/com/google/gwt/dev/util/Util.java | 63 ++++------- .../com/google/gwt/util/tools/Utility.java | 18 ++-- 12 files changed, 135 insertions(+), 163 deletions(-) diff --git a/dev/core/src/com/google/gwt/core/ext/linker/impl/StandardLinkerContext.java b/dev/core/src/com/google/gwt/core/ext/linker/impl/StandardLinkerContext.java index 50884db9eef..66054cc1f3a 100644 --- a/dev/core/src/com/google/gwt/core/ext/linker/impl/StandardLinkerContext.java +++ b/dev/core/src/com/google/gwt/core/ext/linker/impl/StandardLinkerContext.java @@ -52,7 +52,6 @@ import com.google.gwt.dev.resource.ResourceOracle; import com.google.gwt.dev.util.DefaultTextOutput; import com.google.gwt.dev.util.OutputFileSet; -import com.google.gwt.util.tools.Utility; import java.io.BufferedOutputStream; import java.io.File; @@ -521,10 +520,8 @@ public void produceOutput(TreeLogger logger, ArtifactSet artifacts, partialPath = partialPath.substring(1); } } - OutputStream artifactStream = null; - try { - artifactStream = new BufferedOutputStream(out.openForWrite(partialPath, - artifact.getLastModified())); + try (OutputStream artifactStream = new BufferedOutputStream( + out.openForWrite(partialPath, artifact.getLastModified()))) { artifact.writeTo(artifactLogger, artifactStream); } catch (IOException e) { artifactLogger.log(TreeLogger.ERROR, @@ -533,8 +530,6 @@ public void produceOutput(TreeLogger logger, ArtifactSet artifacts, if (visibility != Visibility.Private) { throw new UnableToCompleteException(); } - } finally { - Utility.close(artifactStream); } } } diff --git a/dev/core/src/com/google/gwt/core/ext/soyc/coderef/EntityRecorder.java b/dev/core/src/com/google/gwt/core/ext/soyc/coderef/EntityRecorder.java index fedb2979cff..a39f1ea5d41 100644 --- a/dev/core/src/com/google/gwt/core/ext/soyc/coderef/EntityRecorder.java +++ b/dev/core/src/com/google/gwt/core/ext/soyc/coderef/EntityRecorder.java @@ -38,11 +38,11 @@ import com.google.gwt.thirdparty.json.JSONArray; import com.google.gwt.thirdparty.json.JSONException; import com.google.gwt.thirdparty.json.JSONObject; -import com.google.gwt.util.tools.Utility; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintWriter; +import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Map; import java.util.Map.Entry; @@ -170,14 +170,9 @@ private void recordCodeReferences(DependencyGraphRecorder codeGraph, } private String addArtifactFromJson(Object value, String named) throws IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - PrintWriter writer = new PrintWriter(baos); - writer.write(value.toString()); - Utility.close(writer); - // TODO(ocallau) Must be updated with the correct/final linker SyntheticArtifact artifact = new SyntheticArtifact( - SoycReportLinker.class, named, baos.toByteArray()); + SoycReportLinker.class, named, value.toString().getBytes(StandardCharsets.UTF_8)); artifact.setVisibility(Visibility.LegacyDeploy); toReturn.add(artifact); diff --git a/dev/core/src/com/google/gwt/core/ext/soyc/impl/DependencyRecorder.java b/dev/core/src/com/google/gwt/core/ext/soyc/impl/DependencyRecorder.java index 7dfaf6f208d..359e3d9e109 100644 --- a/dev/core/src/com/google/gwt/core/ext/soyc/impl/DependencyRecorder.java +++ b/dev/core/src/com/google/gwt/core/ext/soyc/impl/DependencyRecorder.java @@ -22,7 +22,6 @@ import com.google.gwt.dev.jjs.ast.JRunAsync; import com.google.gwt.dev.jjs.impl.ControlFlowAnalyzer; import com.google.gwt.dev.jjs.impl.codesplitter.MultipleDependencyGraphRecorder; -import com.google.gwt.util.tools.Utility; import java.io.IOException; import java.io.OutputStream; @@ -108,7 +107,10 @@ public void startDependencyGraph(String identifier, String extnds) { /** * Used to record dependencies of a program. + * + * @deprecated this method is unused internally, and may be removed in a future release. */ + @Deprecated protected void recordDependenciesImpl(TreeLogger logger, JProgram jprogram) { logger = logger.branch(TreeLogger.DEBUG, "Creating dependencies file for the compile report"); @@ -129,7 +131,7 @@ protected void recordDependenciesImpl(TreeLogger logger, JProgram jprogram) { printPost(); flushOutput(); - Utility.close(writer); + writer.close(); } catch (Throwable e) { logger.log(TreeLogger.WARN, "Could not write dependency file; proceeding anyway.", e); diff --git a/dev/core/src/com/google/gwt/core/ext/soyc/impl/SplitPointRecorder.java b/dev/core/src/com/google/gwt/core/ext/soyc/impl/SplitPointRecorder.java index c73b5b01124..a6a408644e9 100644 --- a/dev/core/src/com/google/gwt/core/ext/soyc/impl/SplitPointRecorder.java +++ b/dev/core/src/com/google/gwt/core/ext/soyc/impl/SplitPointRecorder.java @@ -20,7 +20,6 @@ import com.google.gwt.dev.jjs.ast.JRunAsync; import com.google.gwt.dev.jjs.impl.codesplitter.FragmentPartitioningResult; import com.google.gwt.dev.util.HtmlTextOutput; -import com.google.gwt.util.tools.Utility; import java.io.OutputStream; import java.io.OutputStreamWriter; @@ -28,6 +27,8 @@ import java.util.List; import java.util.zip.GZIPOutputStream; +import static java.nio.charset.StandardCharsets.UTF_8; + /** * Records split points to a file for Compile Reports. */ @@ -41,77 +42,75 @@ public static void recordSplitPoints(JProgram jprogram, OutputStream out, TreeLo logger.branch(TreeLogger.TRACE, "Creating split point map file for the compile report"); try { - OutputStreamWriter writer = new OutputStreamWriter(new GZIPOutputStream(out), "UTF-8"); - PrintWriter pw = new PrintWriter(writer); - HtmlTextOutput htmlOut = new HtmlTextOutput(pw, false); - String curLine = ""; - htmlOut.printRaw(curLine); - htmlOut.newline(); - - curLine = ""; - htmlOut.printRaw(curLine); - htmlOut.newline(); - htmlOut.indentIn(); - htmlOut.indentIn(); + try (OutputStreamWriter writer = new OutputStreamWriter(new GZIPOutputStream(out), UTF_8); + PrintWriter pw = new PrintWriter(writer)) { + HtmlTextOutput htmlOut = new HtmlTextOutput(pw, false); + String curLine = ""; + htmlOut.printRaw(curLine); + htmlOut.newline(); - List runAsyncs = jprogram.getRunAsyncs(); - FragmentPartitioningResult partitionResult = jprogram.getFragmentPartitioningResult(); - if (runAsyncs.size() > 0) { - curLine = ""; + curLine = ""; htmlOut.printRaw(curLine); htmlOut.newline(); htmlOut.indentIn(); htmlOut.indentIn(); - for (JRunAsync runAsync : runAsyncs) { - int sp = runAsync.getRunAsyncId(); - if (partitionResult != null) { - sp = partitionResult.getFragmentForRunAsync(sp); - } - String name = runAsync.getName(); - curLine = ""; + + List runAsyncs = jprogram.getRunAsyncs(); + FragmentPartitioningResult partitionResult = jprogram.getFragmentPartitioningResult(); + if (runAsyncs.size() > 0) { + curLine = ""; htmlOut.printRaw(curLine); htmlOut.newline(); - if (logger.isLoggable(TreeLogger.TRACE)) { - logger.log(TreeLogger.TRACE, "Assigning split point #" + sp + " for '" + name + "'"); + htmlOut.indentIn(); + htmlOut.indentIn(); + for (JRunAsync runAsync : runAsyncs) { + int sp = runAsync.getRunAsyncId(); + if (partitionResult != null) { + sp = partitionResult.getFragmentForRunAsync(sp); + } + String name = runAsync.getName(); + curLine = ""; + htmlOut.printRaw(curLine); + htmlOut.newline(); + if (logger.isLoggable(TreeLogger.TRACE)) { + logger.log(TreeLogger.TRACE, "Assigning split point #" + sp + " for '" + name + "'"); + } } + htmlOut.indentOut(); + htmlOut.indentOut(); + curLine = ""; + htmlOut.printRaw(curLine); + htmlOut.newline(); } - htmlOut.indentOut(); - htmlOut.indentOut(); - curLine = ""; - htmlOut.printRaw(curLine); - htmlOut.newline(); - } - if (!jprogram.getInitialFragmentIdSequence().isEmpty()) { - curLine = ""; - htmlOut.printRaw(curLine); - htmlOut.newline(); - htmlOut.indentIn(); + if (!jprogram.getInitialFragmentIdSequence().isEmpty()) { + curLine = ""; + htmlOut.printRaw(curLine); + htmlOut.newline(); + htmlOut.indentIn(); - for (int sp : jprogram.getInitialFragmentIdSequence()) { - if (partitionResult != null) { - sp = partitionResult.getFragmentForRunAsync(sp); + for (int sp : jprogram.getInitialFragmentIdSequence()) { + if (partitionResult != null) { + sp = partitionResult.getFragmentForRunAsync(sp); + } + curLine = ""; + htmlOut.printRaw(curLine); + htmlOut.newline(); } - curLine = ""; + + htmlOut.indentOut(); + curLine = ""; htmlOut.printRaw(curLine); htmlOut.newline(); } htmlOut.indentOut(); - curLine = ""; + htmlOut.indentOut(); + curLine = ""; htmlOut.printRaw(curLine); htmlOut.newline(); } - htmlOut.indentOut(); - htmlOut.indentOut(); - curLine = ""; - htmlOut.printRaw(curLine); - htmlOut.newline(); - - Utility.close(writer); - pw.close(); - logger.log(TreeLogger.DEBUG, "Done"); } catch (Throwable e) { diff --git a/dev/core/src/com/google/gwt/core/ext/soyc/impl/StoryRecorder.java b/dev/core/src/com/google/gwt/core/ext/soyc/impl/StoryRecorder.java index bfa7223d38b..d4607769b0e 100644 --- a/dev/core/src/com/google/gwt/core/ext/soyc/impl/StoryRecorder.java +++ b/dev/core/src/com/google/gwt/core/ext/soyc/impl/StoryRecorder.java @@ -28,7 +28,6 @@ import com.google.gwt.dev.jjs.ast.JMethod; import com.google.gwt.dev.util.Util; import com.google.gwt.thirdparty.guava.common.collect.Lists; -import com.google.gwt.util.tools.Utility; import java.io.IOException; import java.io.OutputStream; @@ -145,7 +144,7 @@ protected void recordStoriesImpl(TreeLogger logger, OutputStream out, storyCache = null; Util.writeUtf8(builder, gzipStream); - Utility.close(gzipStream); + gzipStream.close(); logger.log(TreeLogger.INFO, "Done"); } catch (Throwable e) { diff --git a/dev/core/src/com/google/gwt/dev/MinimalRebuildCacheManager.java b/dev/core/src/com/google/gwt/dev/MinimalRebuildCacheManager.java index 544b99b0902..752cef704c7 100644 --- a/dev/core/src/com/google/gwt/dev/MinimalRebuildCacheManager.java +++ b/dev/core/src/com/google/gwt/dev/MinimalRebuildCacheManager.java @@ -22,7 +22,6 @@ import com.google.gwt.thirdparty.guava.common.io.Closeables; import com.google.gwt.thirdparty.guava.common.util.concurrent.Futures; import com.google.gwt.thirdparty.guava.common.util.concurrent.MoreExecutors; -import com.google.gwt.util.tools.Utility; import com.google.gwt.util.tools.shared.Md5Utils; import com.google.gwt.util.tools.shared.StringUtils; @@ -222,12 +221,11 @@ public Void call() { oldMinimalRebuildCacheFile.getParentFile().mkdirs(); // Write the new cache to disk. - ObjectOutputStream objectOutputStream = null; try { - objectOutputStream = new ObjectOutputStream( - new BufferedOutputStream(new FileOutputStream(newMinimalRebuildCacheFile))); - objectOutputStream.writeObject(minimalRebuildCache); - Utility.close(objectOutputStream); + try (ObjectOutputStream objectOutputStream = new ObjectOutputStream( + new BufferedOutputStream(new FileOutputStream(newMinimalRebuildCacheFile)))) { + objectOutputStream.writeObject(minimalRebuildCache); + } // Replace the old cache file with the new one. oldMinimalRebuildCacheFile.delete(); @@ -236,10 +234,6 @@ public Void call() { logger.log(TreeLogger.WARN, "Unable to update the cache in " + oldMinimalRebuildCacheFile + "."); newMinimalRebuildCacheFile.delete(); - } finally { - if (objectOutputStream != null) { - Utility.close(objectOutputStream); - } } return null; } diff --git a/dev/core/src/com/google/gwt/dev/ServletWriter.java b/dev/core/src/com/google/gwt/dev/ServletWriter.java index 3dcfe8ef114..85c9c858814 100644 --- a/dev/core/src/com/google/gwt/dev/ServletWriter.java +++ b/dev/core/src/com/google/gwt/dev/ServletWriter.java @@ -15,8 +15,6 @@ */ package com.google.gwt.dev; -import com.google.gwt.util.tools.Utility; - import java.io.File; import java.io.FileWriter; import java.io.IOException; @@ -69,22 +67,22 @@ public void realize(File webXml) throws IOException { return; } webXml.getParentFile().mkdirs(); - FileWriter xmlWriter = new FileWriter(webXml); - xmlWriter.write("\n"); - xmlWriter.write("\n"); + try (FileWriter xmlWriter = new FileWriter(webXml)) { + xmlWriter.write("\n"); + xmlWriter.write("\n"); - for (Entry entry : mappings.entrySet()) { - String servletClass = entry.getKey(); - String servletPath = entry.getValue(); - String servletName = servletClass.replace('.', '_'); - xmlWriter.write('\n'); - xmlWriter.write(generateServletTag(servletName, servletClass)); - xmlWriter.write('\n'); - xmlWriter.write(generateServletMappingTag(servletName, servletPath)); - xmlWriter.write('\n'); - } + for (Entry entry : mappings.entrySet()) { + String servletClass = entry.getKey(); + String servletPath = entry.getValue(); + String servletName = servletClass.replace('.', '_'); + xmlWriter.write('\n'); + xmlWriter.write(generateServletTag(servletName, servletClass)); + xmlWriter.write('\n'); + xmlWriter.write(generateServletMappingTag(servletName, servletPath)); + xmlWriter.write('\n'); + } - xmlWriter.write("\n\n"); - Utility.close(xmlWriter); + xmlWriter.write("\n\n"); + } } } diff --git a/dev/core/src/com/google/gwt/dev/javac/PersistentUnitCacheDir.java b/dev/core/src/com/google/gwt/dev/javac/PersistentUnitCacheDir.java index d3bf118be8f..b3f3ed38536 100644 --- a/dev/core/src/com/google/gwt/dev/javac/PersistentUnitCacheDir.java +++ b/dev/core/src/com/google/gwt/dev/javac/PersistentUnitCacheDir.java @@ -27,7 +27,6 @@ import com.google.gwt.thirdparty.guava.common.annotations.VisibleForTesting; import com.google.gwt.thirdparty.guava.common.collect.Lists; import com.google.gwt.thirdparty.guava.common.io.Closeables; -import com.google.gwt.util.tools.Utility; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; @@ -38,6 +37,7 @@ import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; +import java.nio.file.Files; import java.util.Collections; import java.util.List; @@ -381,13 +381,17 @@ boolean writeUnit(TreeLogger logger, CompilationUnit unit) } /** - * Closes the current file and deletes it if it's empty. If no file is open, does nothing. + * Closes the current file and deletes it if it's empty. */ void close(TreeLogger logger) { logger.log(Type.TRACE, "Closing cache file: " + file + " (" + unitsWritten + " units written)"); - Utility.close(stream); + try { + stream.close(); + } catch (IOException e) { + logger.log(Type.WARN, "Error closing compilation unit cache file " + file, e); + } if (unitsWritten == 0) { // Remove useless empty file. @@ -408,7 +412,16 @@ private static ObjectOutputStream openObjectStream(TreeLogger logger, File file) return new ObjectOutputStream(new BufferedOutputStream(fstream)); } catch (IOException e) { logger.log(Type.ERROR, "Can't open persistent unit cache file", e); - Utility.close(fstream); + try { + if (fstream != null) { + fstream.close(); + if (file.exists()) { + Files.delete(file.toPath()); + } + } + } catch (IOException ignored) { + // We can't handle this, and already logged an error + } throw new UnableToCompleteException(); } } diff --git a/dev/core/src/com/google/gwt/dev/javac/StandardGeneratorContext.java b/dev/core/src/com/google/gwt/dev/javac/StandardGeneratorContext.java index 5cc75c37c22..51fef86825e 100644 --- a/dev/core/src/com/google/gwt/dev/javac/StandardGeneratorContext.java +++ b/dev/core/src/com/google/gwt/dev/javac/StandardGeneratorContext.java @@ -46,7 +46,6 @@ import com.google.gwt.dev.util.log.speedtracer.SpeedTracerLogger; import com.google.gwt.dev.util.log.speedtracer.SpeedTracerLogger.Event; import com.google.gwt.thirdparty.guava.common.io.Files; -import com.google.gwt.util.tools.Utility; import java.io.ByteArrayOutputStream; import java.io.File; @@ -215,15 +214,11 @@ public GeneratedUnitWithFile(File file, StringWriter pw, String typeName) { @Override public void commit(TreeLogger logger) { super.commit(logger); - FileOutputStream fos = null; - try { - fos = new FileOutputStream(file); + try (FileOutputStream fos = new FileOutputStream(file)) { diskCache.transferToStream(sourceToken, fos); } catch (IOException e) { logger.log(TreeLogger.WARN, "Error writing out generated unit at '" + file.getAbsolutePath() + "': " + e); - } finally { - Utility.close(fos); } } diff --git a/dev/core/src/com/google/gwt/dev/shell/BrowserChannel.java b/dev/core/src/com/google/gwt/dev/shell/BrowserChannel.java index f5daec74756..39f1f70771c 100644 --- a/dev/core/src/com/google/gwt/dev/shell/BrowserChannel.java +++ b/dev/core/src/com/google/gwt/dev/shell/BrowserChannel.java @@ -19,7 +19,6 @@ import com.google.gwt.dev.shell.BrowserChannel.SessionHandler.SpecialDispatchId; import com.google.gwt.dev.shell.BrowserChannel.Value.ValueType; import com.google.gwt.thirdparty.guava.common.io.Closeables; -import com.google.gwt.util.tools.Utility; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; @@ -1510,8 +1509,18 @@ protected BrowserChannel(InputStream inputStream, OutputStream outputStream, public void endSession() { Closeables.closeQuietly(streamFromOtherSide); - Utility.close(streamToOtherSide); - Utility.close(socket); + try { + streamToOtherSide.close(); + } catch (IOException ignored) { + // ignore exception, we just want to close everything regardless of errors + } + if (socket != null) { + try { + socket.close(); + } catch (IOException ignored) { + // ignore exception, we just want to close everything regardless of errors + } + } } /** diff --git a/dev/core/src/com/google/gwt/dev/util/Util.java b/dev/core/src/com/google/gwt/dev/util/Util.java index 859080d5a1d..1d66ae84de1 100644 --- a/dev/core/src/com/google/gwt/dev/util/Util.java +++ b/dev/core/src/com/google/gwt/dev/util/Util.java @@ -37,7 +37,6 @@ import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; -import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; @@ -60,6 +59,8 @@ import java.security.NoSuchAlgorithmException; import java.util.Collection; +import static java.nio.charset.StandardCharsets.UTF_8; + /** * A smattering of useful methods. Methods in this class are candidates for * being moved to {@link com.google.gwt.util.tools.Utility} if they would be @@ -134,7 +135,7 @@ public static void copy(InputStream is, OutputStream os) throws IOException { copyNoClose(is, os); } finally { Closeables.closeQuietly(is); - Utility.close(os); + os.close(); } } @@ -698,22 +699,16 @@ public static void writeBytesToFile(TreeLogger logger, File where, byte[] what) */ public static void writeBytesToFile(TreeLogger logger, File where, byte[][] what) throws UnableToCompleteException { - FileOutputStream f = null; Throwable caught; - try { - // No need to check mkdirs result because an IOException will occur anyway - where.getParentFile().mkdirs(); - f = new FileOutputStream(where); + // No need to check mkdirs result because an IOException will occur anyway + where.getParentFile().mkdirs(); + try (FileOutputStream f = new FileOutputStream(where)) { for (int i = 0; i < what.length; i++) { f.write(what[i]); } return; - } catch (FileNotFoundException e) { - caught = e; } catch (IOException e) { caught = e; - } finally { - Utility.close(f); } String msg = "Unable to write file '" + where + "'"; logger.log(TreeLogger.ERROR, msg, caught); @@ -726,18 +721,15 @@ public static void writeBytesToFile(TreeLogger logger, File where, public static void writeObjectAsFile(TreeLogger logger, File file, Object... objects) throws UnableToCompleteException { Event writeObjectAsFileEvent = SpeedTracerLogger.start(CompilerEventType.WRITE_OBJECT_AS_FILE); - FileOutputStream stream = null; - try { - // No need to check mkdirs result because an IOException will occur anyway - file.getParentFile().mkdirs(); - stream = new FileOutputStream(file); + // No need to check mkdirs result because an IOException will occur anyway + file.getParentFile().mkdirs(); + try (FileOutputStream stream = new FileOutputStream(file)) { writeObjectToStream(stream, objects); } catch (IOException e) { logger.log(TreeLogger.ERROR, "Unable to write file: " + file.getAbsolutePath(), e); throw new UnableToCompleteException(); } finally { - Utility.close(stream); writeObjectAsFileEvent.end(); } } @@ -756,46 +748,27 @@ public static void writeObjectToStream(OutputStream stream, Object... objects) } public static boolean writeStringAsFile(File file, String string) { - FileOutputStream stream = null; - OutputStreamWriter writer = null; - BufferedWriter buffered = null; - try { - // No need to check mkdirs result because an IOException will occur anyway - file.getParentFile().mkdirs(); - stream = new FileOutputStream(file); - writer = new OutputStreamWriter(stream, DEFAULT_ENCODING); - buffered = new BufferedWriter(writer); + // No need to check mkdirs result because an IOException will occur anyway + file.getParentFile().mkdirs(); + try (FileOutputStream stream = new FileOutputStream(file); + BufferedWriter buffered = new BufferedWriter(new OutputStreamWriter(stream, UTF_8))) { buffered.write(string); } catch (IOException e) { return false; - } finally { - Utility.close(buffered); - Utility.close(writer); - Utility.close(stream); } return true; } public static void writeStringAsFile(TreeLogger logger, File file, String string) throws UnableToCompleteException { - FileOutputStream stream = null; - OutputStreamWriter writer = null; - BufferedWriter buffered = null; - try { - stream = new FileOutputStream(file); - writer = new OutputStreamWriter(stream, DEFAULT_ENCODING); - buffered = new BufferedWriter(writer); - // No need to check mkdirs result because an IOException will occur anyway - file.getParentFile().mkdirs(); + // No need to check mkdirs result because an IOException will occur anyway + file.getParentFile().mkdirs(); + try (FileOutputStream stream = new FileOutputStream(file); + BufferedWriter buffered = new BufferedWriter(new OutputStreamWriter(stream, UTF_8))) { buffered.write(string); } catch (IOException e) { - logger.log(TreeLogger.ERROR, "Unable to write file: " - + file.getAbsolutePath(), e); + logger.log(TreeLogger.ERROR, "Unable to write file: " + file.getAbsolutePath(), e); throw new UnableToCompleteException(); - } finally { - Utility.close(buffered); - Utility.close(writer); - Utility.close(stream); } } diff --git a/dev/core/src/com/google/gwt/util/tools/Utility.java b/dev/core/src/com/google/gwt/util/tools/Utility.java index c991d703abf..8b865b9d87d 100644 --- a/dev/core/src/com/google/gwt/util/tools/Utility.java +++ b/dev/core/src/com/google/gwt/util/tools/Utility.java @@ -57,6 +57,7 @@ public final class Utility { * Helper that ignores exceptions during close, because what are you going to * do? */ + @Deprecated public static void close(AutoCloseable closeable) { try { if (closeable != null) { @@ -232,10 +233,9 @@ public static void streamOut(InputStream in, OutputStream out, int bufferSize) } public static void writeTemplateBinaryFile(File file, byte[] contents) throws IOException { - - FileOutputStream o = new FileOutputStream(file); - o.write(contents); - close(o); + try (FileOutputStream o = new FileOutputStream(file)) { + o.write(contents); + } } public static void writeTemplateFile(File file, String contents, @@ -252,12 +252,12 @@ public static void writeTemplateFile(File file, String contents, replacedContents = replacedContents.replaceAll(replaceThis, withThis); } - PrintWriter pw = new PrintWriter(file); - LineNumberReader lnr = new LineNumberReader(new StringReader(replacedContents)); - for (String line = lnr.readLine(); line != null; line = lnr.readLine()) { - pw.println(line); + try (PrintWriter pw = new PrintWriter(file)) { + LineNumberReader lnr = new LineNumberReader(new StringReader(replacedContents)); + for (String line = lnr.readLine(); line != null; line = lnr.readLine()) { + pw.println(line); + } } - close(pw); } private static void computeInstallationPath() {