Index: trunk/src/org/openstreetmap/josm/actions/ImageryAdjustAction.java
===================================================================
--- trunk/src/org/openstreetmap/josm/actions/ImageryAdjustAction.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/actions/ImageryAdjustAction.java	(revision 7033)
@@ -17,4 +17,6 @@
 import java.awt.event.MouseListener;
 import java.awt.event.MouseMotionListener;
+import java.util.Formatter;
+import java.util.Locale;
 
 import javax.swing.JLabel;
@@ -236,7 +238,9 @@
             int precision = Main.getProjection().getDefaultZoomInPPD() >= 1.0 ? 2 : 7;
             // US locale to force decimal separator to be '.'
-            tOffset.setText(new java.util.Formatter(java.util.Locale.US).format(
+            try (Formatter us = new Formatter(Locale.US)) {
+                tOffset.setText(us.format(
                     "%1." + precision + "f; %1." + precision + "f",
                     layer.getDx(), layer.getDy()).toString());
+            }
         }
 
Index: trunk/src/org/openstreetmap/josm/actions/OpenFileAction.java
===================================================================
--- trunk/src/org/openstreetmap/josm/actions/OpenFileAction.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/actions/OpenFileAction.java	(revision 7033)
@@ -292,6 +292,5 @@
 
                 for (File urlFile: urlFiles) {
-                    try {
-                        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(urlFile), Utils.UTF_8));
+                    try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(urlFile), Utils.UTF_8))) {
                         String line;
                         while ((line = reader.readLine()) != null) {
Index: trunk/src/org/openstreetmap/josm/actions/SessionLoadAction.java
===================================================================
--- trunk/src/org/openstreetmap/josm/actions/SessionLoadAction.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/actions/SessionLoadAction.java	(revision 7033)
@@ -153,9 +153,6 @@
                         file = File.createTempFile("session_", ".joz", Utils.getJosmTempDir());
                         tempFile = true;
-                        FileOutputStream out = new FileOutputStream(file);
-                        try {
+                        try (FileOutputStream out = new FileOutputStream(file)) {
                             Utils.copyStream(is, out);
-                        } finally {
-                            Utils.close(out);
                         }
                     }
Index: trunk/src/org/openstreetmap/josm/data/AutosaveTask.java
===================================================================
--- trunk/src/org/openstreetmap/josm/data/AutosaveTask.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/data/AutosaveTask.java	(revision 7033)
@@ -157,9 +157,7 @@
             try {
                 if (result.createNewFile()) {
-                    try {
-                        File pidFile = new File(autosaveDir, filename+".pid");
-                        PrintStream ps = new PrintStream(pidFile, "UTF-8");
+                    File pidFile = new File(autosaveDir, filename+".pid");
+                    try (PrintStream ps = new PrintStream(pidFile, "UTF-8")) {
                         ps.println(ManagementFactory.getRuntimeMXBean().getName());
-                        Utils.close(ps);
                     } catch (Throwable t) {
                         Main.error(t);
@@ -305,6 +303,5 @@
                 File pidFile = getPidFile(file);
                 if (pidFile.exists()) {
-                    try {
-                        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(pidFile), Utils.UTF_8));
+                    try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(pidFile), Utils.UTF_8))) {
                         try {
                             String jvmId = reader.readLine();
Index: trunk/src/org/openstreetmap/josm/data/CustomConfigurator.java
===================================================================
--- trunk/src/org/openstreetmap/josm/data/CustomConfigurator.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/data/CustomConfigurator.java	(revision 7033)
@@ -427,5 +427,7 @@
                 String fileDir = file.getParentFile().getAbsolutePath();
                 if (fileDir!=null) engine.eval("scriptDir='"+normalizeDirName(fileDir) +"';");
-                openAndReadXML(new BufferedInputStream(new FileInputStream(file)));
+                try (InputStream is = new BufferedInputStream(new FileInputStream(file))) {
+                    openAndReadXML(is);
+                }
             } catch (Exception ex) {
                 log("Error reading custom preferences: " + ex.getMessage());
@@ -445,6 +447,4 @@
             } catch (Exception ex) {
                 log("Error reading custom preferences: "+ex.getMessage());
-            } finally {
-                Utils.close(is);
             }
             log("-- Reading complete --");
@@ -460,5 +460,5 @@
                 engine.eval("homeDir='"+normalizeDirName(Main.pref.getPreferencesDir()) +"';");
                 engine.eval("josmVersion="+Version.getInstance().getVersion()+";");
-                String className =  CustomConfigurator.class.getName();
+                String className = CustomConfigurator.class.getName();
                 engine.eval("API.messageBox="+className+".messageBox");
                 engine.eval("API.askText=function(text) { return String("+className+".askForText(text));}");
Index: trunk/src/org/openstreetmap/josm/data/Preferences.java
===================================================================
--- trunk/src/org/openstreetmap/josm/data/Preferences.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/data/Preferences.java	(revision 7033)
@@ -11,4 +11,5 @@
 import java.io.FileOutputStream;
 import java.io.IOException;
+import java.io.InputStream;
 import java.io.InputStreamReader;
 import java.io.OutputStreamWriter;
@@ -719,6 +720,5 @@
 
     /**
-     * Called after every put. In case of a problem, do nothing but output the error
-     * in log.
+     * Called after every put. In case of a problem, do nothing but output the error in log.
      */
     public void save() throws IOException {
@@ -736,8 +736,8 @@
         }
 
-        final PrintWriter out = new PrintWriter(new OutputStreamWriter(
-                new FileOutputStream(prefFile + "_tmp"), Utils.UTF_8), false);
-        out.print(toXML(false));
-        Utils.close(out);
+        try (PrintWriter out = new PrintWriter(new OutputStreamWriter(
+                new FileOutputStream(prefFile + "_tmp"), Utils.UTF_8), false)) {
+            out.print(toXML(false));
+        }
 
         File tmpFile = new File(prefFile + "_tmp");
@@ -748,5 +748,4 @@
         setCorrectPermissions(backupFile);
     }
-
 
     private void setCorrectPermissions(File file) {
@@ -761,12 +760,9 @@
         settingsMap.clear();
         File pref = getPreferenceFile();
-        BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(pref), Utils.UTF_8));
-        try {
+        try (BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(pref), Utils.UTF_8))) {
             validateXML(in);
-            Utils.close(in);
-            in = new BufferedReader(new InputStreamReader(new FileInputStream(pref), Utils.UTF_8));
+        }
+        try (BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(pref), Utils.UTF_8))) {
             fromXML(in);
-        } finally {
-            Utils.close(in);
         }
         updateSystemProperties();
@@ -1359,7 +1355,9 @@
     public void validateXML(Reader in) throws Exception {
         SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
-        Schema schema = factory.newSchema(new StreamSource(new MirroredInputStream("resource://data/preferences.xsd")));
-        Validator validator = schema.newValidator();
-        validator.validate(new StreamSource(in));
+        try (InputStream xsdStream = new MirroredInputStream("resource://data/preferences.xsd")) {
+            Schema schema = factory.newSchema(new StreamSource(xsdStream));
+            Validator validator = schema.newValidator();
+            validator.validate(new StreamSource(in));
+        }
     }
 
Index: trunk/src/org/openstreetmap/josm/data/Version.java
===================================================================
--- trunk/src/org/openstreetmap/josm/data/Version.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/data/Version.java	(revision 7033)
@@ -38,12 +38,9 @@
         String s = null;
         try {
-            BufferedReader in = Utils.openURLReader(resource);
             StringBuilder sb = new StringBuilder();
-            try {
+            try (BufferedReader in = Utils.openURLReader(resource)) {
                 for (String line = in.readLine(); line != null; line = in.readLine()) {
                     sb.append(line).append("\n");
                 }
-            } finally {
-                Utils.close(in);
             }
             s = sb.toString();
Index: trunk/src/org/openstreetmap/josm/data/imagery/WmsCache.java
===================================================================
--- trunk/src/org/openstreetmap/josm/data/imagery/WmsCache.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/data/imagery/WmsCache.java	(revision 7033)
@@ -111,48 +111,39 @@
     private String getCacheDirectory(String url) {
         String cacheDirName = null;
-        InputStream fis = null;
-        OutputStream fos = null;
-        try {
-            Properties layersIndex = new Properties();
-            File layerIndexFile = new File(cacheDirPath(), LAYERS_INDEX_FILENAME);
-            try {
-                fis = new FileInputStream(layerIndexFile);
-                layersIndex.load(fis);
-            } catch (FileNotFoundException e) {
-                Main.error("Unable to load layers index for wms cache (file " + layerIndexFile + " not found)");
+        Properties layersIndex = new Properties();
+        File layerIndexFile = new File(cacheDirPath(), LAYERS_INDEX_FILENAME);
+        try (InputStream fis = new FileInputStream(layerIndexFile)) {
+            layersIndex.load(fis);
+        } catch (FileNotFoundException e) {
+            Main.error("Unable to load layers index for wms cache (file " + layerIndexFile + " not found)");
+        } catch (IOException e) {
+            Main.error("Unable to load layers index for wms cache");
+            Main.error(e);
+        }
+
+        for (Object propKey: layersIndex.keySet()) {
+            String s = (String)propKey;
+            if (url.equals(layersIndex.getProperty(s))) {
+                cacheDirName = s;
+                break;
+            }
+        }
+
+        if (cacheDirName == null) {
+            int counter = 0;
+            while (true) {
+                counter++;
+                if (!layersIndex.keySet().contains(String.valueOf(counter))) {
+                    break;
+                }
+            }
+            cacheDirName = String.valueOf(counter);
+            layersIndex.setProperty(cacheDirName, url);
+            try (OutputStream fos = new FileOutputStream(layerIndexFile)) {
+                layersIndex.store(fos, "");
             } catch (IOException e) {
-                Main.error("Unable to load layers index for wms cache");
+                Main.error("Unable to save layer index for wms cache");
                 Main.error(e);
             }
-
-            for (Object propKey: layersIndex.keySet()) {
-                String s = (String)propKey;
-                if (url.equals(layersIndex.getProperty(s))) {
-                    cacheDirName = s;
-                    break;
-                }
-            }
-
-            if (cacheDirName == null) {
-                int counter = 0;
-                while (true) {
-                    counter++;
-                    if (!layersIndex.keySet().contains(String.valueOf(counter))) {
-                        break;
-                    }
-                }
-                cacheDirName = String.valueOf(counter);
-                layersIndex.setProperty(cacheDirName, url);
-                try {
-                    fos = new FileOutputStream(layerIndexFile);
-                    layersIndex.store(fos, "");
-                } catch (IOException e) {
-                    Main.error("Unable to save layer index for wms cache");
-                    Main.error(e);
-                }
-            }
-        } finally {
-            Utils.close(fos);
-            Utils.close(fis);
         }
 
@@ -181,5 +172,8 @@
                     WmsCacheType.class.getClassLoader());
             Unmarshaller unmarshaller = context.createUnmarshaller();
-            WmsCacheType cacheEntries = (WmsCacheType)unmarshaller.unmarshal(new FileInputStream(indexFile));
+            WmsCacheType cacheEntries;
+            try (InputStream is = new FileInputStream(indexFile)) {
+                cacheEntries = (WmsCacheType)unmarshaller.unmarshal(is);
+            }
             totalFileSize = cacheEntries.getTotalFileSize();
             if (cacheEntries.getTileSize() != tileSize) {
@@ -292,5 +286,7 @@
                     WmsCacheType.class.getClassLoader());
             Marshaller marshaller = context.createMarshaller();
-            marshaller.marshal(index, new FileOutputStream(new File(cacheDir, INDEX_FILENAME)));
+            try (OutputStream fos = new FileOutputStream(new File(cacheDir, INDEX_FILENAME))) {
+                marshaller.marshal(index, fos);
+            }
         } catch (Exception e) {
             Main.error("Failed to save wms-cache file");
@@ -302,5 +298,4 @@
         return new File(cacheDir, projection.cacheDirectory + "/" + entry.filename);
     }
-
 
     private BufferedImage loadImage(ProjectionEntries projectionEntries, CacheEntry entry) throws IOException {
@@ -524,9 +519,6 @@
             totalFileSize += imageFile.length();
         } else {
-            OutputStream os = new BufferedOutputStream(new FileOutputStream(imageFile));
-            try {
+            try (OutputStream os = new BufferedOutputStream(new FileOutputStream(imageFile))) {
                 totalFileSize += Utils.copyStream(imageData, os);
-            } finally {
-                Utils.close(os);
             }
         }
Index: trunk/src/org/openstreetmap/josm/data/projection/Projections.java
===================================================================
--- trunk/src/org/openstreetmap/josm/data/projection/Projections.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/data/projection/Projections.java	(revision 7033)
@@ -132,13 +132,13 @@
     private static void loadInits() {
         Pattern epsgPattern = Pattern.compile("<(\\d+)>(.*)<>");
-        BufferedReader r = null;
-        try {
+        try (
             InputStream in = new MirroredInputStream("resource://data/projection/epsg");
-            r = new BufferedReader(new InputStreamReader(in, Utils.UTF_8));
+            BufferedReader r = new BufferedReader(new InputStreamReader(in, Utils.UTF_8));
+        ) {
             String line, lastline = "";
             while ((line = r.readLine()) != null) {
                 line = line.trim();
                 if (!line.startsWith("#") && !line.isEmpty()) {
-                    if (!lastline.startsWith("#")) throw new AssertionError();
+                    if (!lastline.startsWith("#")) throw new AssertionError("EPSG file seems corrupted");
                     String name = lastline.substring(1).trim();
                     Matcher m = epsgPattern.matcher(line);
@@ -153,6 +153,4 @@
         } catch (IOException ex) {
             throw new RuntimeException(ex);
-        } finally {
-            Utils.close(r);
         }
     }
Index: trunk/src/org/openstreetmap/josm/data/projection/datum/NTV2GridShiftFileWrapper.java
===================================================================
--- trunk/src/org/openstreetmap/josm/data/projection/datum/NTV2GridShiftFileWrapper.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/data/projection/datum/NTV2GridShiftFileWrapper.java	(revision 7033)
@@ -48,6 +48,5 @@
     public NTV2GridShiftFile getShiftFile() {
         if (instance == null) {
-            try {
-                InputStream is = new MirroredInputStream(gridFileName);
+            try (InputStream is = new MirroredInputStream(gridFileName)) {
                 instance = new NTV2GridShiftFile();
                 instance.loadGridShiftFile(is, false);
@@ -58,4 +57,3 @@
         return instance;
     }
-
 }
Index: trunk/src/org/openstreetmap/josm/data/validation/OsmValidator.java
===================================================================
--- trunk/src/org/openstreetmap/josm/data/validation/OsmValidator.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/data/validation/OsmValidator.java	(revision 7033)
@@ -171,7 +171,5 @@
             File file = new File(getValidatorDir() + "ignorederrors");
             if (file.exists()) {
-                BufferedReader in = null;
-                try {
-                    in = new BufferedReader(new InputStreamReader(new FileInputStream(file), Utils.UTF_8));
+                try (BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file), Utils.UTF_8))) {
                     for (String line = in.readLine(); line != null; line = in.readLine()) {
                         ignoredErrors.add(line);
@@ -181,6 +179,4 @@
                 } catch (final IOException e) {
                     Main.error(e);
-                } finally {
-                    Utils.close(in);
                 }
             }
@@ -197,7 +193,6 @@
 
     public static void saveIgnoredErrors() {
-        PrintWriter out = null;
-        try {
-            out = new PrintWriter(new OutputStreamWriter(new FileOutputStream(getValidatorDir() + "ignorederrors"), Utils.UTF_8), false);
+        try (PrintWriter out = new PrintWriter(new OutputStreamWriter(
+                new FileOutputStream(getValidatorDir() + "ignorederrors"), Utils.UTF_8), false)) {
             for (String e : ignoredErrors) {
                 out.println(e);
@@ -205,6 +200,4 @@
         } catch (IOException e) {
             Main.error(e);
-        } finally {
-            Utils.close(out);
         }
     }
Index: trunk/src/org/openstreetmap/josm/data/validation/tests/MapCSSTagChecker.java
===================================================================
--- trunk/src/org/openstreetmap/josm/data/validation/tests/MapCSSTagChecker.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/data/validation/tests/MapCSSTagChecker.java	(revision 7033)
@@ -453,9 +453,6 @@
                     Main.info(tr("Adding {0} to tag checker", i));
                 }
-                MirroredInputStream s = new MirroredInputStream(i);
-                try {
+                try (MirroredInputStream s = new MirroredInputStream(i)) {
                     addMapCSS(new BufferedReader(UTFInputStreamReader.create(s)));
-                } finally {
-                    Utils.close(s);
                 }
             } catch (IOException ex) {
Index: trunk/src/org/openstreetmap/josm/data/validation/tests/OpeningHourTest.java
===================================================================
--- trunk/src/org/openstreetmap/josm/data/validation/tests/OpeningHourTest.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/data/validation/tests/OpeningHourTest.java	(revision 7033)
@@ -5,4 +5,5 @@
 
 import java.io.InputStreamReader;
+import java.io.Reader;
 import java.util.ArrayList;
 import java.util.Arrays;
@@ -51,20 +52,23 @@
         super.initialize();
         if (ENGINE != null) {
-            ENGINE.eval(new InputStreamReader(new MirroredInputStream("resource://data/validator/opening_hours.js"), Utils.UTF_8));
-            // fake country/state to not get errors on holidays
-            ENGINE.eval("var nominatimJSON = {address: {state: 'Bayern', country_code: 'de'}};");
-            ENGINE.eval(
-                    "var oh = function (value, mode) {" +
-                    " try {" +
-                    "    var r= new opening_hours(value, nominatimJSON, mode);" +
-                    "    r.getErrors = function() {return [];};" +
-                    "    return r;" +
-                    "  } catch(err) {" +
-                    "    return {" +
-                    "      getWarnings: function() {return [];}," +
-                    "      getErrors: function() {return [err.toString()]}" +
-                    "    };" +
-                    "  }" +
-                    "};");
+            try (Reader reader = new InputStreamReader(
+                    new MirroredInputStream("resource://data/validator/opening_hours.js"), Utils.UTF_8)) {
+                ENGINE.eval(reader);
+                // fake country/state to not get errors on holidays
+                ENGINE.eval("var nominatimJSON = {address: {state: 'Bayern', country_code: 'de'}};");
+                ENGINE.eval(
+                        "var oh = function (value, mode) {" +
+                        " try {" +
+                        "    var r= new opening_hours(value, nominatimJSON, mode);" +
+                        "    r.getErrors = function() {return [];};" +
+                        "    return r;" +
+                        "  } catch(err) {" +
+                        "    return {" +
+                        "      getWarnings: function() {return [];}," +
+                        "      getErrors: function() {return [err.toString()]}" +
+                        "    };" +
+                        "  }" +
+                        "};");
+            }
         } else {
             Main.warn("Unable to initialize OpeningHourTest because no JavaScript engine has been found");
Index: trunk/src/org/openstreetmap/josm/data/validation/tests/TagChecker.java
===================================================================
--- trunk/src/org/openstreetmap/josm/data/validation/tests/TagChecker.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/data/validation/tests/TagChecker.java	(revision 7033)
@@ -54,5 +54,4 @@
 import org.openstreetmap.josm.tools.GBC;
 import org.openstreetmap.josm.tools.MultiMap;
-import org.openstreetmap.josm.tools.Utils;
 
 /**
@@ -165,9 +164,8 @@
         String errorSources = "";
         for (String source : Main.pref.getCollection(PREF_SOURCES, DEFAULT_SOURCES)) {
-            BufferedReader reader = null;
-            try {
+            try (
                 MirroredInputStream s = new MirroredInputStream(source);
-                reader = new BufferedReader(UTFInputStreamReader.create(s));
-
+                BufferedReader reader = new BufferedReader(UTFInputStreamReader.create(s));
+            ) {
                 String okValue = null;
                 boolean tagcheckerfile = false;
@@ -242,6 +240,4 @@
             } catch (IOException e) {
                 errorSources += source + "\n";
-            } finally {
-                Utils.close(reader);
             }
         }
Index: trunk/src/org/openstreetmap/josm/gui/MainApplication.java
===================================================================
--- trunk/src/org/openstreetmap/josm/gui/MainApplication.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/gui/MainApplication.java	(revision 7033)
@@ -13,4 +13,5 @@
 import java.awt.event.WindowEvent;
 import java.io.File;
+import java.io.InputStream;
 import java.net.Authenticator;
 import java.net.ProxySelector;
@@ -339,6 +340,6 @@
             for (String i : args.get(Option.LOAD_PREFERENCES)) {
                 info("Reading preferences from " + i);
-                try {
-                    config.openAndReadXML(Utils.openURL(new URL(i)));
+                try (InputStream is = Utils.openURL(new URL(i))) {
+                    config.openAndReadXML(is);
                 } catch (Exception ex) {
                     throw new RuntimeException(ex);
Index: trunk/src/org/openstreetmap/josm/gui/dialogs/MapPaintDialog.java
===================================================================
--- trunk/src/org/openstreetmap/josm/gui/dialogs/MapPaintDialog.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/gui/dialogs/MapPaintDialog.java	(revision 7033)
@@ -24,4 +24,5 @@
 import java.io.InputStream;
 import java.io.InputStreamReader;
+import java.io.OutputStream;
 import java.util.ArrayList;
 import java.util.Arrays;
@@ -516,11 +517,10 @@
                 getProgressMonitor().indeterminateSubTask(
                         tr("Save style ''{0}'' as ''{1}''", s.getDisplayString(), file.getPath()));
-                BufferedInputStream bis = null;
-                BufferedOutputStream bos = null;
                 try {
                     InputStream in = s.getSourceInputStream();
-                    try {
-                        bis = new BufferedInputStream(in);
-                        bos = new BufferedOutputStream(new FileOutputStream(file));
+                    try (
+                        InputStream bis = new BufferedInputStream(in);
+                        OutputStream bos = new BufferedOutputStream(new FileOutputStream(file))
+                    ) {
                         byte[] buffer = new byte[4096];
                         int length;
@@ -533,7 +533,4 @@
                 } catch (IOException e) {
                     error = true;
-                } finally {
-                    Utils.close(bis);
-                    Utils.close(bos);
                 }
             }
Index: trunk/src/org/openstreetmap/josm/gui/download/PlaceSelection.java
===================================================================
--- trunk/src/org/openstreetmap/josm/gui/download/PlaceSelection.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/gui/download/PlaceSelection.java	(revision 7033)
@@ -15,4 +15,5 @@
 import java.io.InputStream;
 import java.io.InputStreamReader;
+import java.io.Reader;
 import java.net.HttpURLConnection;
 import java.net.URL;
@@ -368,9 +369,13 @@
                 }
                 connection.setConnectTimeout(Main.pref.getInteger("socket.timeout.connect",15)*1000);
-                InputStream inputStream = connection.getInputStream();
-                InputSource inputSource = new InputSource(new InputStreamReader(inputStream, Utils.UTF_8));
-                NameFinderResultParser parser = new NameFinderResultParser();
-                SAXParserFactory.newInstance().newSAXParser().parse(inputSource, parser);
-                this.data = parser.getResult();
+                try (
+                    InputStream inputStream = connection.getInputStream();
+                    Reader reader = new InputStreamReader(inputStream, Utils.UTF_8);
+                ) {
+                    InputSource inputSource = new InputSource(reader);
+                    NameFinderResultParser parser = new NameFinderResultParser();
+                    SAXParserFactory.newInstance().newSAXParser().parse(inputSource, parser);
+                    this.data = parser.getResult();
+                }
             } catch(Exception e) {
                 if (canceled)
Index: trunk/src/org/openstreetmap/josm/gui/help/HelpBrowser.java
===================================================================
--- trunk/src/org/openstreetmap/josm/gui/help/HelpBrowser.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/gui/help/HelpBrowser.java	(revision 7033)
@@ -135,12 +135,10 @@
     protected StyleSheet buildStyleSheet() {
         StyleSheet ss = new StyleSheet();
-        BufferedReader reader = new BufferedReader(
+        StringBuilder css = new StringBuilder();
+        try (BufferedReader reader = new BufferedReader(
                 new InputStreamReader(
-                        getClass().getResourceAsStream("/data/help-browser.css"),
-                        Utils.UTF_8
+                        getClass().getResourceAsStream("/data/help-browser.css"), Utils.UTF_8
                 )
-        );
-        StringBuilder css = new StringBuilder();
-        try {
+        )) {
             String line = null;
             while ((line = reader.readLine()) != null) {
@@ -148,10 +146,8 @@
                 css.append("\n");
             }
-        } catch(Exception e) {
+        } catch (Exception e) {
             Main.error(tr("Failed to read CSS file ''help-browser.css''. Exception is: {0}", e.toString()));
             Main.error(e);
             return ss;
-        } finally {
-            Utils.close(reader);
         }
         ss.addRule(css.toString());
Index: trunk/src/org/openstreetmap/josm/gui/io/DownloadFileTask.java
===================================================================
--- trunk/src/org/openstreetmap/josm/gui/io/DownloadFileTask.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/gui/io/DownloadFileTask.java	(revision 7033)
@@ -83,6 +83,4 @@
      */
     public void download() throws DownloadException {
-        OutputStream out = null;
-        InputStream in = null;
         try {
             if (mkdir) {
@@ -105,20 +103,22 @@
             progressMonitor.subTask(tr("Downloading File {0}: {1} bytes...", file.getName(),size));
 
-            in = downloadConnection.getInputStream();
-            out = new FileOutputStream(file);
-            byte[] buffer = new byte[32768];
-            int count=0;
-            int p1=0, p2=0;
-            for (int read = in.read(buffer); read != -1; read = in.read(buffer)) {
-                out.write(buffer, 0, read);
-                count+=read;
-                if (canceled) break;
-                p2 = 100 * count / size;
-                if (p2!=p1) {
-                    progressMonitor.setTicks(p2);
-                    p1=p2;
+            try (
+                InputStream in = downloadConnection.getInputStream();
+                OutputStream out = new FileOutputStream(file)
+            ) {
+                byte[] buffer = new byte[32768];
+                int count=0;
+                int p1=0, p2=0;
+                for (int read = in.read(buffer); read != -1; read = in.read(buffer)) {
+                    out.write(buffer, 0, read);
+                    count+=read;
+                    if (canceled) break;
+                    p2 = 100 * count / size;
+                    if (p2!=p1) {
+                        progressMonitor.setTicks(p2);
+                        p1=p2;
+                    }
                 }
             }
-            Utils.close(out);
             if (!canceled) {
                 Main.info(tr("Download finished"));
@@ -139,5 +139,4 @@
         } finally {
             closeConnectionIfNeeded();
-            Utils.close(out);
         }
     }
@@ -170,19 +169,15 @@
      */
     public static void unzipFileRecursively(File file, String dir) throws IOException {
-        OutputStream os = null;
-        InputStream is = null;
-        ZipFile zf = null;
-        try {
-            zf = new ZipFile(file);
-            Enumeration<?> es = zf.entries();
-            ZipEntry ze;
+        try (ZipFile zf = new ZipFile(file)) {
+            Enumeration<? extends ZipEntry> es = zf.entries();
             while (es.hasMoreElements()) {
-                ze = (ZipEntry) es.nextElement();
+                ZipEntry ze = es.nextElement();
                 File newFile = new File(dir, ze.getName());
                 if (ze.isDirectory()) {
                     newFile.mkdirs();
-                } else {
-                    is = zf.getInputStream(ze);
-                    os = new BufferedOutputStream(new FileOutputStream(newFile));
+                } else try (
+                    InputStream is = zf.getInputStream(ze);
+                    OutputStream os = new BufferedOutputStream(new FileOutputStream(newFile))
+                ) {
                     byte[] buffer = new byte[8192];
                     int read;
@@ -190,12 +185,7 @@
                         os.write(buffer, 0, read);
                     }
-                    Utils.close(os);
-                    Utils.close(is);
                 }
             }
-        } finally {
-            Utils.close(zf);
         }
     }
 }
-
Index: trunk/src/org/openstreetmap/josm/gui/layer/TMSLayer.java
===================================================================
--- trunk/src/org/openstreetmap/josm/gui/layer/TMSLayer.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/gui/layer/TMSLayer.java	(revision 7033)
@@ -326,9 +326,9 @@
             protected byte[] updateData() throws IOException {
                 URL u = getAttributionUrl();
-                UTFInputStreamReader in = UTFInputStreamReader.create(Utils.openURL(u));
-                String r = new Scanner(in).useDelimiter("\\A").next();
-                Utils.close(in);
-                Main.info("Successfully loaded Bing attribution data.");
-                return r.getBytes("utf-8");
+                try (Scanner scanner = new Scanner(UTFInputStreamReader.create(Utils.openURL(u)))) {
+                    String r = scanner.useDelimiter("\\A").next();
+                    Main.info("Successfully loaded Bing attribution data.");
+                    return r.getBytes("UTF-8");
+                }
             }
         }
Index: trunk/src/org/openstreetmap/josm/gui/layer/geoimage/CorrelateGpxWithImages.java
===================================================================
--- trunk/src/org/openstreetmap/josm/gui/layer/geoimage/CorrelateGpxWithImages.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/gui/layer/geoimage/CorrelateGpxWithImages.java	(revision 7033)
@@ -21,4 +21,5 @@
 import java.io.File;
 import java.io.FileInputStream;
+import java.io.FileNotFoundException;
 import java.io.IOException;
 import java.io.InputStream;
@@ -171,11 +172,5 @@
                 }
                 GpxData data = null;
-                try {
-                    InputStream iStream;
-                    if (sel.getName().toLowerCase().endsWith(".gpx.gz")) {
-                        iStream = new GZIPInputStream(new FileInputStream(sel));
-                    } else {
-                        iStream = new FileInputStream(sel);
-                    }
+                try (InputStream iStream = createInputStream(sel)) {
                     GpxReader reader = new GpxReader(iStream);
                     reader.parse(false);
@@ -211,4 +206,12 @@
             } finally {
                 outerPanel.setCursor(Cursor.getDefaultCursor());
+            }
+        }
+
+        private InputStream createInputStream(File sel) throws IOException, FileNotFoundException {
+            if (sel.getName().toLowerCase().endsWith(".gpx.gz")) {
+                return new GZIPInputStream(new FileInputStream(sel));
+            } else {
+                return new FileInputStream(sel);
             }
         }
Index: trunk/src/org/openstreetmap/josm/gui/mappaint/mapcss/MapCSSStyleSource.java
===================================================================
--- trunk/src/org/openstreetmap/josm/gui/mappaint/mapcss/MapCSSStyleSource.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/gui/mappaint/mapcss/MapCSSStyleSource.java	(revision 7033)
@@ -75,6 +75,5 @@
         init();
         rules.clear();
-        try {
-            InputStream in = getSourceInputStream();
+        try (InputStream in = getSourceInputStream()) {
             try {
                 // evaluate @media { ... } blocks
Index: trunk/src/org/openstreetmap/josm/gui/mappaint/xml/XmlStyleSource.java
===================================================================
--- trunk/src/org/openstreetmap/josm/gui/mappaint/xml/XmlStyleSource.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/gui/mappaint/xml/XmlStyleSource.java	(revision 7033)
@@ -75,7 +75,8 @@
         init();
         try {
-            InputStream in = getSourceInputStream();
-            try {
-                InputStreamReader reader = new InputStreamReader(in, Utils.UTF_8);
+            try (
+                InputStream in = getSourceInputStream();
+                InputStreamReader reader = new InputStreamReader(in, Utils.UTF_8)
+            ) {
                 XmlObjectParser parser = new XmlObjectParser(new XmlStyleSourceHandler(this));
                 parser.startWithValidation(reader,
@@ -83,8 +84,5 @@
                         "resource://data/mappaint-style.xsd");
                 while (parser.hasNext());
-            } finally {
-                closeSourceInputStream(in);
-            }
-
+            }
         } catch (IOException e) {
             Main.warn(tr("Failed to load Mappaint styles from ''{0}''. Exception was: {1}", url, e.toString()));
@@ -377,4 +375,3 @@
         }
     }
-
 }
Index: trunk/src/org/openstreetmap/josm/gui/tagging/TaggingPresetReader.java
===================================================================
--- trunk/src/org/openstreetmap/josm/gui/tagging/TaggingPresetReader.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/gui/tagging/TaggingPresetReader.java	(revision 7033)
@@ -225,18 +225,15 @@
     public static Collection<TaggingPreset> readAll(String source, boolean validate) throws SAXException, IOException {
         Collection<TaggingPreset> tp;
-        MirroredInputStream s = new MirroredInputStream(source, null, PRESET_MIME_TYPES);
-        try {
-            InputStream zip = s.findZipEntryInputStream("xml","preset");
-            if(zip != null) {
+        try (
+            MirroredInputStream s = new MirroredInputStream(source, null, PRESET_MIME_TYPES);
+            // zip may be null, but Java 7 allows it: https://blogs.oracle.com/darcy/entry/project_coin_null_try_with
+            InputStream zip = s.findZipEntryInputStream("xml", "preset")
+        ) {
+            if (zip != null) {
                 zipIcons = s.getFile();
             }
-            InputStreamReader r = new InputStreamReader(zip == null ? s : zip, Utils.UTF_8);
-            try {
+            try (InputStreamReader r = new InputStreamReader(zip == null ? s : zip, Utils.UTF_8)) {
                 tp = readAll(new BufferedReader(r), validate);
-            } finally {
-                Utils.close(r);
-            }
-        } finally {
-            Utils.close(s);
+            }
         }
         return tp;
Index: trunk/src/org/openstreetmap/josm/io/BoundingBoxDownloader.java
===================================================================
--- trunk/src/org/openstreetmap/josm/io/BoundingBoxDownloader.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/io/BoundingBoxDownloader.java	(revision 7033)
@@ -12,5 +12,4 @@
 import org.openstreetmap.josm.gui.progress.ProgressMonitor;
 import org.openstreetmap.josm.tools.CheckParameterUtil;
-import org.openstreetmap.josm.tools.Utils;
 import org.xml.sax.SAXException;
 
@@ -48,23 +47,25 @@
         for (int i = 0;!done;++i) {
             progressMonitor.subTask(tr("Downloading points {0} to {1}...", i * 5000, ((i + 1) * 5000)));
-            InputStream in = getInputStream(url+i, progressMonitor.createSubTaskMonitor(1, true));
-            if (in == null) {
-                break;
+            try (InputStream in = getInputStream(url+i, progressMonitor.createSubTaskMonitor(1, true))) {
+                if (in == null) {
+                    break;
+                }
+                progressMonitor.setTicks(0);
+                GpxReader reader = new GpxReader(in);
+                gpxParsedProperly = reader.parse(false);
+                GpxData currentGpx = reader.getGpxData();
+                if (result == null) {
+                    result = currentGpx;
+                } else if (currentGpx.hasTrackPoints()) {
+                    result.mergeFrom(currentGpx);
+                } else{
+                    done = true;
+                }
             }
-            progressMonitor.setTicks(0);
-            GpxReader reader = new GpxReader(in);
-            gpxParsedProperly = reader.parse(false);
-            GpxData currentGpx = reader.getGpxData();
-            if (result == null) {
-                result = currentGpx;
-            } else if (currentGpx.hasTrackPoints()) {
-                result.mergeFrom(currentGpx);
-            } else{
-                done = true;
-            }
-            Utils.close(in);
             activeConnection = null;
         }
-        result.fromServer = true;
+        if (result != null) {
+            result.fromServer = true;
+        }
         return result;
     }
@@ -113,5 +114,4 @@
     public DataSet parseOsm(ProgressMonitor progressMonitor) throws OsmTransferException {
         progressMonitor.beginTask(tr("Contacting OSM Server..."), 10);
-        InputStream in = null;
         try {
             DataSet ds = null;
@@ -119,13 +119,17 @@
             if (crosses180th) {
                 // API 0.6 does not support requests crossing the 180th meridian, so make two requests
-                in = getInputStream(getRequestForBbox(lon1, lat1, 180.0, lat2), progressMonitor.createSubTaskMonitor(9, false));
-                if (in == null)
-                    return null;
-                ds = OsmReader.parseDataSet(in, progressMonitor.createSubTaskMonitor(1, false));
+                DataSet ds2 = null;
 
-                in = getInputStream(getRequestForBbox(-180.0, lat1, lon2, lat2), progressMonitor.createSubTaskMonitor(9, false));
-                if (in == null)
-                    return null;
-                DataSet ds2 = OsmReader.parseDataSet(in, progressMonitor.createSubTaskMonitor(1, false));
+                try (InputStream in = getInputStream(getRequestForBbox(lon1, lat1, 180.0, lat2), progressMonitor.createSubTaskMonitor(9, false))) {
+                    if (in == null)
+                        return null;
+                    ds = OsmReader.parseDataSet(in, progressMonitor.createSubTaskMonitor(1, false));
+                }
+
+                try (InputStream in = getInputStream(getRequestForBbox(-180.0, lat1, lon2, lat2), progressMonitor.createSubTaskMonitor(9, false))) {
+                    if (in == null)
+                        return null;
+                    ds2 = OsmReader.parseDataSet(in, progressMonitor.createSubTaskMonitor(1, false));
+                }
                 if (ds2 == null)
                     return null;
@@ -134,8 +138,9 @@
             } else {
                 // Simple request
-                in = getInputStream(getRequestForBbox(lon1, lat1, lon2, lat2), progressMonitor.createSubTaskMonitor(9, false));
-                if (in == null)
-                    return null;
-                ds = OsmReader.parseDataSet(in, progressMonitor.createSubTaskMonitor(1, false));
+                try (InputStream in = getInputStream(getRequestForBbox(lon1, lat1, lon2, lat2), progressMonitor.createSubTaskMonitor(9, false))) {
+                    if (in == null)
+                        return null;
+                    ds = OsmReader.parseDataSet(in, progressMonitor.createSubTaskMonitor(1, false));
+                }
             }
             return ds;
@@ -146,5 +151,4 @@
         } finally {
             progressMonitor.finishTask();
-            Utils.close(in);
             activeConnection = null;
         }
Index: trunk/src/org/openstreetmap/josm/io/CacheCustomContent.java
===================================================================
--- trunk/src/org/openstreetmap/josm/io/CacheCustomContent.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/io/CacheCustomContent.java	(revision 7033)
@@ -145,13 +145,9 @@
      */
     private void loadFromDisk() throws T {
-        BufferedInputStream input = null;
-        try {
-            input = new BufferedInputStream(new FileInputStream(path));
+        try (BufferedInputStream input = new BufferedInputStream(new FileInputStream(path))) {
             this.data = new byte[input.available()];
             input.read(this.data);
         } catch (IOException e) {
             this.data = updateForce();
-        } finally {
-            Utils.close(input);
         }
     }
@@ -161,13 +157,9 @@
      */
     private void saveToDisk() {
-        BufferedOutputStream output = null;
-        try {
-            output = new BufferedOutputStream(new FileOutputStream(path));
+        try (BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(path))) {
             output.write(this.data);
             output.flush();
-        } catch(Exception e) {
+        } catch (IOException e) {
             Main.error(e);
-        } finally {
-            Utils.close(output);
         }
     }
Index: trunk/src/org/openstreetmap/josm/io/CacheFiles.java
===================================================================
--- trunk/src/org/openstreetmap/josm/io/CacheFiles.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/io/CacheFiles.java	(revision 7033)
@@ -114,5 +114,7 @@
 
             byte[] bytes = new byte[(int) data.length()];
-            new RandomAccessFile(data, "r").readFully(bytes);
+            try (RandomAccessFile raf = new RandomAccessFile(data, "r")) {
+                raf.readFully(bytes);
+            }
             return bytes;
         } catch (Exception e) {
@@ -135,9 +137,6 @@
             }
             // rws also updates the file meta-data, i.e. last mod time
-            RandomAccessFile raf = new RandomAccessFile(f, "rws");
-            try {
+            try (RandomAccessFile raf = new RandomAccessFile(f, "rws")) {
                 raf.write(data);
-            } finally {
-                Utils.close(raf);
             }
         } catch (Exception e) {
Index: trunk/src/org/openstreetmap/josm/io/Compression.java
===================================================================
--- trunk/src/org/openstreetmap/josm/io/Compression.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/io/Compression.java	(revision 7033)
@@ -75,4 +75,5 @@
      * @throws IOException
      */
+    @SuppressWarnings("resource")
     public static InputStream getUncompressedFileInputStream(File file) throws IOException {
         return byExtension(file.getName()).getUncompressedInputStream(new FileInputStream(file));
@@ -114,4 +115,5 @@
      * @throws IOException
      */
+    @SuppressWarnings("resource")
     public static OutputStream getCompressedFileOutputStream(File file) throws IOException {
         return byExtension(file.getName()).getCompressedOutputStream(new FileOutputStream(file));
Index: trunk/src/org/openstreetmap/josm/io/GeoJSONExporter.java
===================================================================
--- trunk/src/org/openstreetmap/josm/io/GeoJSONExporter.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/io/GeoJSONExporter.java	(revision 7033)
@@ -21,4 +21,7 @@
             "json,geojson", "json", tr("GeoJSON Files") + " (*.json *.geojson)");
 
+    /**
+     * Constructs a new {@code GeoJSONExporter}.
+     */
     public GeoJSONExporter() {
         super(FILE_FILTER);
@@ -29,9 +32,6 @@
         if (layer instanceof OsmDataLayer) {
             String json = new GeoJSONWriter((OsmDataLayer) layer).write();
-            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), Utils.UTF_8));
-            try {
+            try (Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), Utils.UTF_8))) {
                 out.write(json);
-            } finally {
-                Utils.close(out);
             }
         } else {
Index: trunk/src/org/openstreetmap/josm/io/GpxImporter.java
===================================================================
--- trunk/src/org/openstreetmap/josm/io/GpxImporter.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/io/GpxImporter.java	(revision 7033)
@@ -76,8 +76,7 @@
     @Override
     public void importData(File file, ProgressMonitor progressMonitor) throws IOException {
-        final InputStream is = Compression.getUncompressedFileInputStream(file);
         final String fileName = file.getName();
 
-        try {
+        try (InputStream is = Compression.getUncompressedFileInputStream(file)) {
             GpxReader r = new GpxReader(is);
             boolean parsedProperly = r.parse(true);
Index: trunk/src/org/openstreetmap/josm/io/GpxReader.java
===================================================================
--- trunk/src/org/openstreetmap/josm/io/GpxReader.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/io/GpxReader.java	(revision 7033)
@@ -507,9 +507,11 @@
 
     /**
-     * Parse the input stream and store the result in trackData and markerData
+     * Constructs a new {@code GpxReader}, which can later parse the input stream 
+     * and store the result in trackData and markerData
      *
      * @param source the source input stream
      * @throws IOException if an IO error occurs, e.g. the input stream is closed.
      */
+    @SuppressWarnings("resource")
     public GpxReader(InputStream source) throws IOException {
         Reader utf8stream = UTFInputStreamReader.create(source);
Index: trunk/src/org/openstreetmap/josm/io/GpxWriter.java
===================================================================
--- trunk/src/org/openstreetmap/josm/io/GpxWriter.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/io/GpxWriter.java	(revision 7033)
@@ -11,4 +11,6 @@
 import java.util.Map;
 import java.util.Map.Entry;
+
+import javax.xml.XMLConstants;
 
 import org.openstreetmap.josm.data.Bounds;
@@ -67,5 +69,5 @@
         out.println("<gpx version=\"1.1\" creator=\"JOSM GPX export\" xmlns=\"http://www.topografix.com/GPX/1/1\"\n" +
                 (hasExtensions ? String.format("    xmlns:josm=\"%s\"%n", JOSM_EXTENSIONS_NAMESPACE_URI) : "") +
-                "    xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \n" +
+                "    xmlns:xsi=\""+XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI+"\" \n" +
                 "    xsi:schemaLocation=\"http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd\">");
         indent = "  ";
Index: trunk/src/org/openstreetmap/josm/io/MirroredInputStream.java
===================================================================
--- trunk/src/org/openstreetmap/josm/io/MirroredInputStream.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/io/MirroredInputStream.java	(revision 7033)
@@ -11,4 +11,5 @@
 import java.io.IOException;
 import java.io.InputStream;
+import java.io.OutputStream;
 import java.net.HttpURLConnection;
 import java.net.MalformedURLException;
@@ -184,4 +185,5 @@
     }
 
+    @SuppressWarnings("resource")
     private Pair<String, InputStream> findZipEntryImpl(String extension, String namepart) {
         if (file == null)
@@ -293,21 +295,17 @@
         String localPath = "mirror_" + a;
         destDirFile = new File(destDir, localPath + ".tmp");
-        BufferedOutputStream bos = null;
-        BufferedInputStream bis = null;
         try {
             HttpURLConnection con = connectFollowingRedirect(url, httpAccept);
-            bis = new BufferedInputStream(con.getInputStream());
-            FileOutputStream fos = new FileOutputStream(destDirFile);
-            bos = new BufferedOutputStream(fos);
-            byte[] buffer = new byte[4096];
-            int length;
-            while ((length = bis.read(buffer)) > -1) {
-                bos.write(buffer, 0, length);
-            }
-            Utils.close(bos);
-            bos = null;
-            /* close fos as well to be sure! */
-            Utils.close(fos);
-            fos = null;
+            try (
+                InputStream bis = new BufferedInputStream(con.getInputStream());
+                OutputStream fos = new FileOutputStream(destDirFile);
+                OutputStream bos = new BufferedOutputStream(fos)
+            ) {
+                byte[] buffer = new byte[4096];
+                int length;
+                while ((length = bis.read(buffer)) > -1) {
+                    bos.write(buffer, 0, length);
+                }
+            }
             localFile = new File(destDir, localPath);
             if(Main.platform.rename(destDirFile, localFile)) {
@@ -325,7 +323,4 @@
                 throw e;
             }
-        } finally {
-            Utils.close(bis);
-            Utils.close(bos);
         }
 
Index: trunk/src/org/openstreetmap/josm/io/MultiFetchServerObjectReader.java
===================================================================
--- trunk/src/org/openstreetmap/josm/io/MultiFetchServerObjectReader.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/io/MultiFetchServerObjectReader.java	(revision 7033)
@@ -5,4 +5,5 @@
 import static org.openstreetmap.josm.tools.I18n.trn;
 
+import java.io.IOException;
 import java.io.InputStream;
 import java.net.HttpURLConnection;
@@ -506,12 +507,17 @@
         protected FetchResult multiGetIdPackage(OsmPrimitiveType type, Set<Long> pkg, ProgressMonitor progressMonitor) throws OsmTransferException {
             String request = buildRequestString(type, pkg);
-            final InputStream in = getInputStream(request, NullProgressMonitor.INSTANCE);
-            if (in == null) return null;
-            progressMonitor.subTask(tr("Downloading OSM data..."));
-            try {
-                return new FetchResult(OsmReader.parseDataSet(in, progressMonitor.createSubTaskMonitor(pkg.size(), false)), null);
-            } catch (Exception e) {
-                throw new OsmTransferException(e);
-            }
+            FetchResult result = null;
+            try (InputStream in = getInputStream(request, NullProgressMonitor.INSTANCE)) {
+                if (in == null) return null;
+                progressMonitor.subTask(tr("Downloading OSM data..."));
+                try {
+                    result = new FetchResult(OsmReader.parseDataSet(in, progressMonitor.createSubTaskMonitor(pkg.size(), false)), null);
+                } catch (Exception e) {
+                    throw new OsmTransferException(e);
+                }
+            } catch (IOException ex) {
+                Main.warn(ex);
+            }
+            return result;
         }
 
@@ -527,12 +533,17 @@
         protected DataSet singleGetId(OsmPrimitiveType type, long id, ProgressMonitor progressMonitor) throws OsmTransferException {
             String request = buildRequestString(type, id);
-            final InputStream in = getInputStream(request, NullProgressMonitor.INSTANCE);
-            if (in == null) return null;
-            progressMonitor.subTask(tr("Downloading OSM data..."));
-            try {
-                return OsmReader.parseDataSet(in, progressMonitor.createSubTaskMonitor(1, false));
-            } catch (Exception e) {
-                throw new OsmTransferException(e);
-            }
+            DataSet result = null;
+            try (InputStream in = getInputStream(request, NullProgressMonitor.INSTANCE)) {
+                if (in == null) return null;
+                progressMonitor.subTask(tr("Downloading OSM data..."));
+                try {
+                    result = OsmReader.parseDataSet(in, progressMonitor.createSubTaskMonitor(1, false));
+                } catch (Exception e) {
+                    throw new OsmTransferException(e);
+                }
+            } catch (IOException ex) {
+                Main.warn(ex);
+            }
+            return result;
         }
 
Index: trunk/src/org/openstreetmap/josm/io/NMEAImporter.java
===================================================================
--- trunk/src/org/openstreetmap/josm/io/NMEAImporter.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/io/NMEAImporter.java	(revision 7033)
@@ -7,4 +7,5 @@
 import java.io.FileInputStream;
 import java.io.IOException;
+import java.io.InputStream;
 
 import javax.swing.JOptionPane;
@@ -35,24 +36,26 @@
     public void importData(File file, ProgressMonitor progressMonitor) throws IOException {
         final String fn = file.getName();
-        final NmeaReader r = new NmeaReader(new FileInputStream(file));
-        if (r.getNumberOfCoordinates() > 0) {
-            r.data.storageFile = file;
-            final GpxLayer gpxLayer = new GpxLayer(r.data, fn, true);
-            final File fileFinal = file;
-
-            GuiHelper.runInEDT(new Runnable() {
-                @Override
-                public void run() {
-                    Main.main.addLayer(gpxLayer);
-                    if (Main.pref.getBoolean("marker.makeautomarkers", true)) {
-                        MarkerLayer ml = new MarkerLayer(r.data, tr("Markers from {0}", fn), fileFinal, gpxLayer);
-                        if (!ml.data.isEmpty()) {
-                            Main.main.addLayer(ml);
+        try (InputStream fis = new FileInputStream(file)) {
+            final NmeaReader r = new NmeaReader(fis);
+            if (r.getNumberOfCoordinates() > 0) {
+                r.data.storageFile = file;
+                final GpxLayer gpxLayer = new GpxLayer(r.data, fn, true);
+                final File fileFinal = file;
+    
+                GuiHelper.runInEDT(new Runnable() {
+                    @Override
+                    public void run() {
+                        Main.main.addLayer(gpxLayer);
+                        if (Main.pref.getBoolean("marker.makeautomarkers", true)) {
+                            MarkerLayer ml = new MarkerLayer(r.data, tr("Markers from {0}", fn), fileFinal, gpxLayer);
+                            if (!ml.data.isEmpty()) {
+                                Main.main.addLayer(ml);
+                            }
                         }
                     }
-                }
-            });
+                });
+            }
+            showNmeaInfobox(r.getNumberOfCoordinates() > 0, r);
         }
-        showNmeaInfobox(r.getNumberOfCoordinates() > 0, r);
     }
 
Index: trunk/src/org/openstreetmap/josm/io/OsmApi.java
===================================================================
--- trunk/src/org/openstreetmap/josm/io/OsmApi.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/io/OsmApi.java	(revision 7033)
@@ -290,12 +290,15 @@
     private String toXml(IPrimitive o, boolean addBody) {
         StringWriter swriter = new StringWriter();
-        OsmWriter osmWriter = OsmWriterFactory.createOsmWriter(new PrintWriter(swriter), true, version);
-        swriter.getBuffer().setLength(0);
-        osmWriter.setWithBody(addBody);
-        osmWriter.setChangeset(changeset);
-        osmWriter.header();
-        o.accept(osmWriter);
-        osmWriter.footer();
-        osmWriter.flush();
+        try (OsmWriter osmWriter = OsmWriterFactory.createOsmWriter(new PrintWriter(swriter), true, version)) {
+            swriter.getBuffer().setLength(0);
+            osmWriter.setWithBody(addBody);
+            osmWriter.setChangeset(changeset);
+            osmWriter.header();
+            o.accept(osmWriter);
+            osmWriter.footer();
+            osmWriter.flush();
+        } catch (IOException e) {
+            Main.warn(e);
+        }
         return swriter.toString();
     }
@@ -308,10 +311,13 @@
     private String toXml(Changeset s) {
         StringWriter swriter = new StringWriter();
-        OsmWriter osmWriter = OsmWriterFactory.createOsmWriter(new PrintWriter(swriter), true, version);
-        swriter.getBuffer().setLength(0);
-        osmWriter.header();
-        osmWriter.visit(s);
-        osmWriter.footer();
-        osmWriter.flush();
+        try (OsmWriter osmWriter = OsmWriterFactory.createOsmWriter(new PrintWriter(swriter), true, version)) {
+            swriter.getBuffer().setLength(0);
+            osmWriter.header();
+            osmWriter.visit(s);
+            osmWriter.footer();
+            osmWriter.flush();
+        } catch (IOException e) {
+            Main.warn(e);
+        }
         return swriter.toString();
     }
@@ -657,10 +663,5 @@
                 // If the API returned an error code like 403 forbidden, getInputStream
                 // will fail with an IOException.
-                InputStream i = null;
-                try {
-                    i = activeConnection.getInputStream();
-                } catch (IOException ioe) {
-                    i = activeConnection.getErrorStream();
-                }
+                InputStream i = getConnectionStream();
                 if (i != null) {
                     // the input stream can be null if both the input and the error stream
@@ -722,4 +723,13 @@
     }
 
+    private InputStream getConnectionStream() {
+        try {
+            return activeConnection.getInputStream();
+        } catch (IOException ioe) {
+            Main.warn(ioe);
+            return activeConnection.getErrorStream();
+        }
+    }
+
     /**
      * Replies the API capabilities
Index: trunk/src/org/openstreetmap/josm/io/OsmChangesetContentParser.java
===================================================================
--- trunk/src/org/openstreetmap/josm/io/OsmChangesetContentParser.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/io/OsmChangesetContentParser.java	(revision 7033)
@@ -123,4 +123,5 @@
      * @throws IllegalArgumentException if source is {@code null}.
      */
+    @SuppressWarnings("resource")
     public OsmChangesetContentParser(InputStream source) {
         CheckParameterUtil.ensureParameterNotNull(source, "source");
Index: trunk/src/org/openstreetmap/josm/io/OsmChangesetParser.java
===================================================================
--- trunk/src/org/openstreetmap/josm/io/OsmChangesetParser.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/io/OsmChangesetParser.java	(revision 7033)
@@ -41,5 +41,5 @@
  */
 public final class OsmChangesetParser {
-    private List<Changeset> changesets;
+    private final List<Changeset> changesets;
 
     private OsmChangesetParser() {
@@ -219,4 +219,5 @@
      * @throws IllegalDataException thrown if the an error was found while parsing the data from the source
      */
+    @SuppressWarnings("resource")
     public static List<Changeset> parse(InputStream source, ProgressMonitor progressMonitor) throws IllegalDataException {
         OsmChangesetParser parser = new OsmChangesetParser();
Index: trunk/src/org/openstreetmap/josm/io/OsmExporter.java
===================================================================
--- trunk/src/org/openstreetmap/josm/io/OsmExporter.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/io/OsmExporter.java	(revision 7033)
@@ -23,4 +23,7 @@
 public class OsmExporter extends FileExporter {
 
+    /**
+     * Constructs a new {@code OsmExporter}.
+     */
     public OsmExporter() {
         super(OsmImporter.FILE_FILTER);
@@ -67,16 +70,16 @@
 
             // create outputstream and wrap it with gzip or bzip, if necessary
-            OutputStream out = getOutputStream(file);
-            Writer writer = new OutputStreamWriter(out, Utils.UTF_8);
-
-            OsmWriter w = OsmWriterFactory.createOsmWriter(new PrintWriter(writer), false, layer.data.getVersion());
-            layer.data.getReadLock().lock();
-            try {
-                w.writeLayer(layer);
-            } finally {
-                Utils.close(w);
-                layer.data.getReadLock().unlock();
+            try (
+                OutputStream out = getOutputStream(file);
+                Writer writer = new OutputStreamWriter(out, Utils.UTF_8);
+                OsmWriter w = OsmWriterFactory.createOsmWriter(new PrintWriter(writer), false, layer.data.getVersion());
+            ) {
+                layer.data.getReadLock().lock();
+                try {
+                    w.writeLayer(layer);
+                } finally {
+                    layer.data.getReadLock().unlock();
+                }
             }
-            // FIXME - how to close?
             if (noBackup || !Main.pref.getBoolean("save.keepbackup", false)) {
                 if (tmpFile != null) {
Index: trunk/src/org/openstreetmap/josm/io/OsmReader.java
===================================================================
--- trunk/src/org/openstreetmap/josm/io/OsmReader.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/io/OsmReader.java	(revision 7033)
@@ -587,8 +587,9 @@
             progressMonitor.indeterminateSubTask(tr("Parsing OSM data..."));
 
-            InputStreamReader ir = UTFInputStreamReader.create(source);
-            XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader(ir);
-            setParser(parser);
-            parse();
+            try (InputStreamReader ir = UTFInputStreamReader.create(source)) {
+                XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader(ir);
+                setParser(parser);
+                parse();
+            }
             progressMonitor.worked(1);
 
Index: trunk/src/org/openstreetmap/josm/io/OsmServerBackreferenceReader.java
===================================================================
--- trunk/src/org/openstreetmap/josm/io/OsmServerBackreferenceReader.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/io/OsmServerBackreferenceReader.java	(revision 7033)
@@ -18,5 +18,4 @@
 import org.openstreetmap.josm.gui.progress.ProgressMonitor;
 import org.openstreetmap.josm.tools.CheckParameterUtil;
-import org.openstreetmap.josm.tools.Utils;
 
 /**
@@ -131,5 +130,4 @@
      */
     protected DataSet getReferringWays(ProgressMonitor progressMonitor) throws OsmTransferException {
-        InputStream in = null;
         progressMonitor.beginTask(null, 2);
         try {
@@ -139,9 +137,10 @@
             .append("/").append(id).append("/ways");
 
-            in = getInputStream(sb.toString(), progressMonitor.createSubTaskMonitor(1, true));
-            if (in == null)
-                return null;
-            progressMonitor.subTask(tr("Downloading referring ways ..."));
-            return OsmReader.parseDataSet(in, progressMonitor.createSubTaskMonitor(1, true));
+            try (InputStream in = getInputStream(sb.toString(), progressMonitor.createSubTaskMonitor(1, true))) {
+                if (in == null)
+                    return null;
+                progressMonitor.subTask(tr("Downloading referring ways ..."));
+                return OsmReader.parseDataSet(in, progressMonitor.createSubTaskMonitor(1, true));
+            }
         } catch(OsmTransferException e) {
             throw e;
@@ -152,5 +151,4 @@
         } finally {
             progressMonitor.finishTask();
-            Utils.close(in);
             activeConnection = null;
         }
@@ -165,5 +163,4 @@
      */
     protected DataSet getReferringRelations(ProgressMonitor progressMonitor) throws OsmTransferException {
-        InputStream in = null;
         progressMonitor.beginTask(null, 2);
         try {
@@ -173,9 +170,10 @@
             .append("/").append(id).append("/relations");
 
-            in = getInputStream(sb.toString(), progressMonitor.createSubTaskMonitor(1, true));
-            if (in == null)
-                return null;
-            progressMonitor.subTask(tr("Downloading referring relations ..."));
-            return OsmReader.parseDataSet(in, progressMonitor.createSubTaskMonitor(1, true));
+            try (InputStream in = getInputStream(sb.toString(), progressMonitor.createSubTaskMonitor(1, true))) {
+                if (in == null)
+                    return null;
+                progressMonitor.subTask(tr("Downloading referring relations ..."));
+                return OsmReader.parseDataSet(in, progressMonitor.createSubTaskMonitor(1, true));
+            }
         } catch(OsmTransferException e) {
             throw e;
@@ -186,5 +184,4 @@
         } finally {
             progressMonitor.finishTask();
-            Utils.close(in);
             activeConnection = null;
         }
Index: trunk/src/org/openstreetmap/josm/io/OsmServerChangesetReader.java
===================================================================
--- trunk/src/org/openstreetmap/josm/io/OsmServerChangesetReader.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/io/OsmServerChangesetReader.java	(revision 7033)
@@ -5,4 +5,5 @@
 import static org.openstreetmap.josm.tools.I18n.trn;
 
+import java.io.IOException;
 import java.io.InputStream;
 import java.text.MessageFormat;
@@ -12,4 +13,5 @@
 import java.util.List;
 
+import org.openstreetmap.josm.Main;
 import org.openstreetmap.josm.data.osm.Changeset;
 import org.openstreetmap.josm.data.osm.ChangesetDataSet;
@@ -53,4 +55,5 @@
     public List<Changeset> queryChangesets(ChangesetQuery query, ProgressMonitor monitor) throws OsmTransferException {
         CheckParameterUtil.ensureParameterNotNull(query, "query");
+        List<Changeset> result = null;
         if (monitor == null) {
             monitor = NullProgressMonitor.INSTANCE;
@@ -60,9 +63,12 @@
             StringBuilder sb = new StringBuilder();
             sb.append("changesets?").append(query.getQueryString());
-            InputStream in = getInputStream(sb.toString(), monitor.createSubTaskMonitor(1, true));
-            if (in == null)
-                return null;
-            monitor.indeterminateSubTask(tr("Downloading changesets ..."));
-            return OsmChangesetParser.parse(in, monitor.createSubTaskMonitor(1, true));
+            try (InputStream in = getInputStream(sb.toString(), monitor.createSubTaskMonitor(1, true))) {
+                if (in == null)
+                    return null;
+                monitor.indeterminateSubTask(tr("Downloading changesets ..."));
+                result = OsmChangesetParser.parse(in, monitor.createSubTaskMonitor(1, true));
+            } catch (IOException e) {
+                Main.warn(e);
+            }
         } catch(OsmTransferException e) {
             throw e;
@@ -72,4 +78,5 @@
             monitor.finishTask();
         }
+        return result;
     }
 
@@ -89,16 +96,20 @@
             monitor = NullProgressMonitor.INSTANCE;
         }
+        Changeset result = null;
         try {
             monitor.beginTask(tr("Reading changeset {0} ...",id));
             StringBuilder sb = new StringBuilder();
             sb.append("changeset/").append(id);
-            InputStream in = getInputStream(sb.toString(), monitor.createSubTaskMonitor(1, true));
-            if (in == null)
-                return null;
-            monitor.indeterminateSubTask(tr("Downloading changeset {0} ...", id));
-            List<Changeset> changesets = OsmChangesetParser.parse(in, monitor.createSubTaskMonitor(1, true));
-            if (changesets == null || changesets.isEmpty())
-                return null;
-            return changesets.get(0);
+            try (InputStream in = getInputStream(sb.toString(), monitor.createSubTaskMonitor(1, true))) {
+                if (in == null)
+                    return null;
+                monitor.indeterminateSubTask(tr("Downloading changeset {0} ...", id));
+                List<Changeset> changesets = OsmChangesetParser.parse(in, monitor.createSubTaskMonitor(1, true));
+                if (changesets == null || changesets.isEmpty())
+                    return null;
+                result = changesets.get(0);
+            } catch (IOException e) {
+                Main.warn(e);
+            }
         } catch(OsmTransferException e) {
             throw e;
@@ -108,4 +119,5 @@
             monitor.finishTask();
         }
+        return result;
     }
 
@@ -137,13 +149,16 @@
                 StringBuilder sb = new StringBuilder();
                 sb.append("changeset/").append(id);
-                InputStream in = getInputStream(sb.toString(), monitor.createSubTaskMonitor(1, true));
-                if (in == null)
-                    return null;
-                monitor.indeterminateSubTask(tr("({0}/{1}) Downloading changeset {2} ...", i, ids.size(), id));
-                List<Changeset> changesets = OsmChangesetParser.parse(in, monitor.createSubTaskMonitor(1, true));
-                if (changesets == null || changesets.isEmpty()) {
-                    continue;
+                try (InputStream in = getInputStream(sb.toString(), monitor.createSubTaskMonitor(1, true))) {
+                    if (in == null)
+                        return null;
+                    monitor.indeterminateSubTask(tr("({0}/{1}) Downloading changeset {2} ...", i, ids.size(), id));
+                    List<Changeset> changesets = OsmChangesetParser.parse(in, monitor.createSubTaskMonitor(1, true));
+                    if (changesets == null || changesets.isEmpty()) {
+                        continue;
+                    }
+                    ret.addAll(changesets);
+                } catch (IOException e) {
+                    Main.warn(e);
                 }
-                ret.addAll(changesets);
                 monitor.worked(1);
             }
@@ -173,14 +188,18 @@
             monitor = NullProgressMonitor.INSTANCE;
         }
+        ChangesetDataSet result = null;
         try {
             monitor.beginTask(tr("Downloading changeset content"));
             StringBuilder sb = new StringBuilder();
             sb.append("changeset/").append(id).append("/download");
-            InputStream in = getInputStream(sb.toString(), monitor.createSubTaskMonitor(1, true));
-            if (in == null)
-                return null;
-            monitor.setCustomText(tr("Downloading content for changeset {0} ...", id));
-            OsmChangesetContentParser parser = new OsmChangesetContentParser(in);
-            return parser.parse(monitor.createSubTaskMonitor(1, true));
+            try (InputStream in = getInputStream(sb.toString(), monitor.createSubTaskMonitor(1, true))) {
+                if (in == null)
+                    return null;
+                monitor.setCustomText(tr("Downloading content for changeset {0} ...", id));
+                OsmChangesetContentParser parser = new OsmChangesetContentParser(in);
+                result = parser.parse(monitor.createSubTaskMonitor(1, true));
+            } catch (IOException e) {
+                Main.warn(e);
+            }
         } catch(XmlParsingException e) {
             throw new OsmTransferException(e);
@@ -188,4 +207,5 @@
             monitor.finishTask();
         }
+        return result;
     }
 }
Index: trunk/src/org/openstreetmap/josm/io/OsmServerHistoryReader.java
===================================================================
--- trunk/src/org/openstreetmap/josm/io/OsmServerHistoryReader.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/io/OsmServerHistoryReader.java	(revision 7033)
@@ -12,5 +12,4 @@
 import org.openstreetmap.josm.gui.progress.ProgressMonitor;
 import org.openstreetmap.josm.tools.CheckParameterUtil;
-import org.openstreetmap.josm.tools.Utils;
 
 /**
@@ -56,5 +55,4 @@
      */
     public HistoryDataSet parseHistory(ProgressMonitor progressMonitor) throws OsmTransferException {
-        InputStream in = null;
         progressMonitor.beginTask("");
         try {
@@ -64,10 +62,11 @@
             .append("/").append(id).append("/history");
 
-            in = getInputStream(sb.toString(), progressMonitor.createSubTaskMonitor(1, true));
-            if (in == null)
-                return null;
-            progressMonitor.indeterminateSubTask(tr("Downloading history..."));
-            final OsmHistoryReader reader = new OsmHistoryReader(in);
-            return reader.parse(progressMonitor.createSubTaskMonitor(1, true));
+            try (InputStream in = getInputStream(sb.toString(), progressMonitor.createSubTaskMonitor(1, true))) {
+                if (in == null)
+                    return null;
+                progressMonitor.indeterminateSubTask(tr("Downloading history..."));
+                OsmHistoryReader reader = new OsmHistoryReader(in);
+                return reader.parse(progressMonitor.createSubTaskMonitor(1, true));
+            }
         } catch(OsmTransferException e) {
             throw e;
@@ -78,5 +77,4 @@
         } finally {
             progressMonitor.finishTask();
-            Utils.close(in);
             activeConnection = null;
         }
Index: trunk/src/org/openstreetmap/josm/io/OsmServerObjectReader.java
===================================================================
--- trunk/src/org/openstreetmap/josm/io/OsmServerObjectReader.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/io/OsmServerObjectReader.java	(revision 7033)
@@ -14,5 +14,4 @@
 import org.openstreetmap.josm.gui.progress.ProgressMonitor;
 import org.openstreetmap.josm.tools.CheckParameterUtil;
-import org.openstreetmap.josm.tools.Utils;
 
 /**
@@ -116,5 +115,4 @@
         }
         progressMonitor.beginTask("", 1);
-        InputStream in = null;
         try {
             progressMonitor.indeterminateSubTask(tr("Downloading OSM data..."));
@@ -129,8 +127,9 @@
             }
 
-            in = getInputStream(sb.toString(), progressMonitor.createSubTaskMonitor(1, true));
-            if (in == null)
-                return null;
-            return OsmReader.parseDataSet(in, progressMonitor.createSubTaskMonitor(ProgressMonitor.ALL_TICKS, false));
+            try (InputStream in = getInputStream(sb.toString(), progressMonitor.createSubTaskMonitor(1, true))) {
+                if (in == null)
+                    return null;
+                return OsmReader.parseDataSet(in, progressMonitor.createSubTaskMonitor(ProgressMonitor.ALL_TICKS, false));
+            }
         } catch(OsmTransferException e) {
             if (cancel) return null;
@@ -141,5 +140,4 @@
         } finally {
             progressMonitor.finishTask();
-            Utils.close(in);
             activeConnection = null;
         }
Index: trunk/src/org/openstreetmap/josm/io/OsmServerReader.java
===================================================================
--- trunk/src/org/openstreetmap/josm/io/OsmServerReader.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/io/OsmServerReader.java	(revision 7033)
@@ -114,4 +114,5 @@
      * @throws OsmTransferException thrown if data transfer errors occur
      */
+    @SuppressWarnings("resource")
     protected InputStream getInputStreamRaw(String urlStr, ProgressMonitor progressMonitor, String reason, boolean uncompressAccordingToContentDisposition) throws OsmTransferException {
         try {
Index: trunk/src/org/openstreetmap/josm/io/OsmServerUserInfoReader.java
===================================================================
--- trunk/src/org/openstreetmap/josm/io/OsmServerUserInfoReader.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/io/OsmServerUserInfoReader.java	(revision 7033)
@@ -167,8 +167,9 @@
             monitor.beginTask("");
             monitor.indeterminateSubTask(tr("Reading user info ..."));
-            InputStream in = getInputStream("user/details", monitor.createSubTaskMonitor(1, true), reason);
-            return buildFromXML(
-                    DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(in)
-            );
+            try (InputStream in = getInputStream("user/details", monitor.createSubTaskMonitor(1, true), reason)) {
+                return buildFromXML(
+                        DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(in)
+                );
+            }
         } catch(OsmTransferException e) {
             throw e;
Index: trunk/src/org/openstreetmap/josm/io/WMSLayerExporter.java
===================================================================
--- trunk/src/org/openstreetmap/josm/io/WMSLayerExporter.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/io/WMSLayerExporter.java	(revision 7033)
@@ -10,5 +10,4 @@
 import org.openstreetmap.josm.gui.layer.WMSLayer;
 import org.openstreetmap.josm.tools.CheckParameterUtil;
-import org.openstreetmap.josm.tools.Utils;
 
 /**
@@ -31,9 +30,6 @@
         CheckParameterUtil.ensureParameterNotNull(layer, "layer");
         if (layer instanceof WMSLayer) {
-            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
-            try {
+            try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file))) {
                 ((WMSLayer)layer).writeExternal(oos);
-            } finally {
-                Utils.close(oos);
             }
         }
Index: trunk/src/org/openstreetmap/josm/io/WMSLayerImporter.java
===================================================================
--- trunk/src/org/openstreetmap/josm/io/WMSLayerImporter.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/io/WMSLayerImporter.java	(revision 7033)
@@ -15,5 +15,4 @@
 import org.openstreetmap.josm.gui.util.GuiHelper;
 import org.openstreetmap.josm.tools.CheckParameterUtil;
-import org.openstreetmap.josm.tools.Utils;
 
 /**
@@ -50,11 +49,8 @@
     public void importData(File file, ProgressMonitor progressMonitor) throws IOException, IllegalDataException {
         CheckParameterUtil.ensureParameterNotNull(file, "file");
-        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
-        try {
+        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) {
             wmsLayer.readExternal(ois);
         } catch (ClassNotFoundException e) {
             throw new IllegalDataException(e);
-        } finally {
-            Utils.close(ois);
         }
 
Index: trunk/src/org/openstreetmap/josm/io/imagery/ImageryReader.java
===================================================================
--- trunk/src/org/openstreetmap/josm/io/imagery/ImageryReader.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/io/imagery/ImageryReader.java	(revision 7033)
@@ -51,8 +51,9 @@
             SAXParserFactory factory = SAXParserFactory.newInstance();
             factory.setNamespaceAware(true);
-            InputStream in = new MirroredInputStream(source);
-            InputSource is = new InputSource(UTFInputStreamReader.create(in));
-            factory.newSAXParser().parse(is, parser);
-            return parser.entries;
+            try (InputStream in = new MirroredInputStream(source)) {
+                InputSource is = new InputSource(UTFInputStreamReader.create(in));
+                factory.newSAXParser().parse(is, parser);
+                return parser.entries;
+            }
         } catch (SAXException e) {
             throw e;
Index: trunk/src/org/openstreetmap/josm/io/imagery/WMSGrabber.java
===================================================================
--- trunk/src/org/openstreetmap/josm/io/imagery/WMSGrabber.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/io/imagery/WMSGrabber.java	(revision 7033)
@@ -173,9 +173,6 @@
 
         ByteArrayOutputStream baos = new ByteArrayOutputStream();
-        InputStream is = new ProgressInputStream(conn, null);
-        try {
+        try (InputStream is = new ProgressInputStream(conn, null)) {
             Utils.copyStream(is, baos);
-        } finally {
-            Utils.close(is);
         }
 
@@ -190,6 +187,5 @@
         StringBuilder exception = new StringBuilder();
         InputStream in = conn.getInputStream();
-        BufferedReader br = new BufferedReader(new InputStreamReader(in, Utils.UTF_8));
-        try {
+        try (BufferedReader br = new BufferedReader(new InputStreamReader(in, Utils.UTF_8))) {
             String line = null;
             while( (line = br.readLine()) != null) {
@@ -199,6 +195,4 @@
             }
             return exception.toString();
-        } finally {
-            Utils.close(br);
         }
     }
Index: trunk/src/org/openstreetmap/josm/io/imagery/WMSImagery.java
===================================================================
--- trunk/src/org/openstreetmap/josm/io/imagery/WMSImagery.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/io/imagery/WMSImagery.java	(revision 7033)
@@ -140,7 +140,10 @@
         Main.info("GET " + getCapabilitiesUrl.toString());
         URLConnection openConnection = Utils.openHttpConnection(getCapabilitiesUrl);
-        InputStream inputStream = openConnection.getInputStream();
         StringBuilder ba = new StringBuilder();
-        try (BufferedReader br = new BufferedReader(UTFInputStreamReader.create(inputStream))) {
+        
+        try (
+            InputStream inputStream = openConnection.getInputStream();
+            BufferedReader br = new BufferedReader(UTFInputStreamReader.create(inputStream))
+        ) {
             String line;
             while ((line = br.readLine()) != null) {
@@ -178,6 +181,6 @@
                             return x.getTextContent();
                         }
-                    }
-                    ), new Predicate<String>() {
+                    }),
+                    new Predicate<String>() {
                         @Override
                         public boolean evaluate(String format) {
@@ -209,5 +212,4 @@
             throw new WMSGetCapabilitiesException(e, incomingData);
         }
-
     }
 
Index: trunk/src/org/openstreetmap/josm/io/remotecontrol/RemoteControlHttpServer.java
===================================================================
--- trunk/src/org/openstreetmap/josm/io/remotecontrol/RemoteControlHttpServer.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/io/remotecontrol/RemoteControlHttpServer.java	(revision 7033)
@@ -83,9 +83,8 @@
              Integer.toString(server.getLocalPort()));
         while (true) {
-            try {
-                Socket request = server.accept();
+            try (Socket request = server.accept()) {
                 RequestProcessor.processRequest(request);
-            } catch( SocketException se) {
-                if( !server.isClosed() )
+            } catch (SocketException se) {
+                if (!server.isClosed())
                     Main.error(se);
             } catch (IOException ioe) {
Index: trunk/src/org/openstreetmap/josm/io/remotecontrol/RemoteControlHttpsServer.java
===================================================================
--- trunk/src/org/openstreetmap/josm/io/remotecontrol/RemoteControlHttpsServer.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/io/remotecontrol/RemoteControlHttpsServer.java	(revision 7033)
@@ -56,35 +56,36 @@
                 
                 // Load keystore
-                InputStream in = RemoteControlHttpsServer.class.getResourceAsStream(KEYSTORE_PATH);
-                if (in == null) {
-                    Main.error(tr("Unable to find JOSM keystore at {0}. Remote control will not be available on HTTPS.", KEYSTORE_PATH));
-                } else {
-                    try {
-                        ks.load(in, password);
-                    } finally {
-                        Utils.close(in);
+                try (InputStream in = RemoteControlHttpsServer.class.getResourceAsStream(KEYSTORE_PATH)) {
+                    if (in == null) {
+                        Main.error(tr("Unable to find JOSM keystore at {0}. Remote control will not be available on HTTPS.", KEYSTORE_PATH));
+                    } else {
+                        try {
+                            ks.load(in, password);
+                        } finally {
+                            Utils.close(in);
+                        }
+                        
+                        if (Main.isDebugEnabled()) {
+                            for (Enumeration<String> aliases = ks.aliases(); aliases.hasMoreElements();) {
+                                Main.debug("Alias in keystore: "+aliases.nextElement());
+                            }
+                        }
+    
+                        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
+                        kmf.init(ks, password);
+                        
+                        TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
+                        tmf.init(ks);
+                        
+                        sslContext = SSLContext.getInstance("TLS");
+                        sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
+                        
+                        if (Main.isDebugEnabled()) {
+                            Main.debug("SSL Context protocol: " + sslContext.getProtocol());
+                            Main.debug("SSL Context provider: " + sslContext.getProvider());
+                        }
+                        
+                        initOK = true;
                     }
-                    
-                    if (Main.isDebugEnabled()) {
-                        for (Enumeration<String> aliases = ks.aliases(); aliases.hasMoreElements();) {
-                            Main.debug("Alias in keystore: "+aliases.nextElement());
-                        }
-                    }
-
-                    KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
-                    kmf.init(ks, password);
-                    
-                    TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
-                    tmf.init(ks);
-                    
-                    sslContext = SSLContext.getInstance("TLS");
-                    sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
-                    
-                    if (Main.isDebugEnabled()) {
-                        Main.debug("SSL Context protocol: " + sslContext.getProtocol());
-                        Main.debug("SSL Context provider: " + sslContext.getProvider());
-                    }
-                    
-                    initOK = true;
                 }
             } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | 
@@ -175,6 +176,5 @@
              Integer.toString(server.getLocalPort()));
         while (true) {
-            try {
-                Socket request = server.accept();
+            try (Socket request = server.accept()) {
                 if (Main.isDebugEnabled() && request instanceof SSLSocket) {
                     SSLSocket sslSocket = (SSLSocket) request;
Index: trunk/src/org/openstreetmap/josm/io/session/GpxTracksSessionExporter.java
===================================================================
--- trunk/src/org/openstreetmap/josm/io/session/GpxTracksSessionExporter.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/io/session/GpxTracksSessionExporter.java	(revision 7033)
@@ -179,10 +179,12 @@
     }
 
-    protected void addDataFile(OutputStream out) {
-        Writer writer = new OutputStreamWriter(out, Utils.UTF_8);
-        GpxWriter w = new GpxWriter(new PrintWriter(writer));
-        w.write(layer.data);
-        w.flush();
+    protected void addDataFile(OutputStream out) throws IOException {
+        try (
+            Writer writer = new OutputStreamWriter(out, Utils.UTF_8);
+            GpxWriter w = new GpxWriter(new PrintWriter(writer))
+        ) {
+            w.write(layer.data);
+            w.flush();
+        }
     }
-
 }
Index: trunk/src/org/openstreetmap/josm/io/session/GpxTracksSessionImporter.java
===================================================================
--- trunk/src/org/openstreetmap/josm/io/session/GpxTracksSessionImporter.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/io/session/GpxTracksSessionImporter.java	(revision 7033)
@@ -37,9 +37,10 @@
             }
 
-            InputStream in = support.getInputStream(fileStr);
-            GpxImporter.GpxImporterData importData = GpxImporter.loadLayers(in, support.getFile(fileStr), support.getLayerName(), null, progressMonitor);
-
-            support.addPostLayersTask(importData.getPostLayerTask());
-            return importData.getGpxLayer();
+            try (InputStream in = support.getInputStream(fileStr)) {
+                GpxImporter.GpxImporterData importData = GpxImporter.loadLayers(in, support.getFile(fileStr), support.getLayerName(), null, progressMonitor);
+    
+                support.addPostLayersTask(importData.getPostLayerTask());
+                return importData.getGpxLayer();
+            }
 
         } catch (XPathExpressionException e) {
@@ -47,4 +48,3 @@
         }
     }
-
 }
Index: trunk/src/org/openstreetmap/josm/io/session/MarkerSessionExporter.java
===================================================================
--- trunk/src/org/openstreetmap/josm/io/session/MarkerSessionExporter.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/io/session/MarkerSessionExporter.java	(revision 7033)
@@ -84,9 +84,12 @@
     }
 
-    protected void addDataFile(OutputStream out) {
-        Writer writer = new OutputStreamWriter(out, Utils.UTF_8);
-        MarkerWriter w = new MarkerWriter(new PrintWriter(writer));
-        w.write(layer);
-        w.flush();
+    protected void addDataFile(OutputStream out) throws IOException {
+        try (
+            Writer writer = new OutputStreamWriter(out, Utils.UTF_8);
+            MarkerWriter w = new MarkerWriter(new PrintWriter(writer))
+        ) {
+            w.write(layer);
+            w.flush();
+        }
     }
 
Index: trunk/src/org/openstreetmap/josm/io/session/MarkerSessionImporter.java
===================================================================
--- trunk/src/org/openstreetmap/josm/io/session/MarkerSessionImporter.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/io/session/MarkerSessionImporter.java	(revision 7033)
@@ -41,23 +41,23 @@
             }
 
-            InputStream in = support.getInputStream(fileStr);
-            GpxImporter.GpxImporterData importData = GpxImporter.loadLayers(in, support.getFile(fileStr), support.getLayerName(), null, progressMonitor);
-
-            support.addPostLayersTask(importData.getPostLayerTask());
-
-            GpxLayer gpxLayer = null;
-            List<SessionReader.LayerDependency> deps = support.getLayerDependencies();
-            if (!deps.isEmpty()) {
-                Layer layer = deps.iterator().next().getLayer();
-                if (layer instanceof GpxLayer) {
-                    gpxLayer = (GpxLayer) layer;
+            try (InputStream in = support.getInputStream(fileStr)) {
+                GpxImporter.GpxImporterData importData = GpxImporter.loadLayers(in, support.getFile(fileStr), support.getLayerName(), null, progressMonitor);
+    
+                support.addPostLayersTask(importData.getPostLayerTask());
+    
+                GpxLayer gpxLayer = null;
+                List<SessionReader.LayerDependency> deps = support.getLayerDependencies();
+                if (!deps.isEmpty()) {
+                    Layer layer = deps.iterator().next().getLayer();
+                    if (layer instanceof GpxLayer) {
+                        gpxLayer = (GpxLayer) layer;
+                    }
                 }
+    
+                MarkerLayer markerLayer = importData.getMarkerLayer();
+                markerLayer.fromLayer = gpxLayer;
+    
+                return markerLayer;
             }
-
-            MarkerLayer markerLayer = importData.getMarkerLayer();
-            markerLayer.fromLayer = gpxLayer;
-
-            return markerLayer;
-
         } catch (XPathExpressionException e) {
             throw new RuntimeException(e);
Index: trunk/src/org/openstreetmap/josm/io/session/OsmDataSessionExporter.java
===================================================================
--- trunk/src/org/openstreetmap/josm/io/session/OsmDataSessionExporter.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/io/session/OsmDataSessionExporter.java	(revision 7033)
@@ -212,13 +212,16 @@
     }
 
-    protected void addDataFile(OutputStream out) {
-        Writer writer = new OutputStreamWriter(out, Utils.UTF_8);
-        OsmWriter w = OsmWriterFactory.createOsmWriter(new PrintWriter(writer), false, layer.data.getVersion());
-        layer.data.getReadLock().lock();
-        try {
-            w.writeLayer(layer);
-            w.flush();
-        } finally {
-            layer.data.getReadLock().unlock();
+    protected void addDataFile(OutputStream out) throws IOException {
+        try (
+            Writer writer = new OutputStreamWriter(out, Utils.UTF_8);
+            OsmWriter w = OsmWriterFactory.createOsmWriter(new PrintWriter(writer), false, layer.data.getVersion())
+        ) {
+            layer.data.getReadLock().lock();
+            try {
+                w.writeLayer(layer);
+                w.flush();
+            } finally {
+                layer.data.getReadLock().unlock();
+            }
         }
     }
Index: trunk/src/org/openstreetmap/josm/io/session/OsmDataSessionImporter.java
===================================================================
--- trunk/src/org/openstreetmap/josm/io/session/OsmDataSessionImporter.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/io/session/OsmDataSessionImporter.java	(revision 7033)
@@ -39,10 +39,10 @@
 
             OsmImporter importer = new OsmImporter();
-            InputStream in = support.getInputStream(fileStr);
-            OsmImporter.OsmImporterData importData = importer.loadLayer(in, support.getFile(fileStr), support.getLayerName(), progressMonitor);
-
-            support.addPostLayersTask(importData.getPostLayerTask());
-            return importData.getLayer();
-
+            try (InputStream in = support.getInputStream(fileStr)) {
+                OsmImporter.OsmImporterData importData = importer.loadLayer(in, support.getFile(fileStr), support.getLayerName(), progressMonitor);
+    
+                support.addPostLayersTask(importData.getPostLayerTask());
+                return importData.getLayer();
+            }
         } catch (XPathExpressionException e) {
             throw new RuntimeException(e);
Index: trunk/src/org/openstreetmap/josm/io/session/SessionReader.java
===================================================================
--- trunk/src/org/openstreetmap/josm/io/session/SessionReader.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/io/session/SessionReader.java	(revision 7033)
@@ -553,10 +553,14 @@
         }
 
-        InputStream josIS = null;
-
+        try (InputStream josIS = createInputStream(sessionFile, zip)) {
+            loadSession(josIS, sessionFile.toURI(), zip, progressMonitor);
+        }
+    }
+
+    private InputStream createInputStream(File sessionFile, boolean zip) throws IOException, IllegalDataException {
         if (zip) {
             try {
                 zipFile = new ZipFile(sessionFile);
-                josIS = getZipInputStream(zipFile);
+                return getZipInputStream(zipFile);
             } catch (ZipException ze) {
                 throw new IOException(ze);
@@ -564,11 +568,9 @@
         } else {
             try {
-                josIS = new FileInputStream(sessionFile);
+                return new FileInputStream(sessionFile);
             } catch (FileNotFoundException ex) {
                 throw new IOException(ex);
             }
         }
-
-        loadSession(josIS, sessionFile.toURI(), zip, progressMonitor);
     }
 
Index: trunk/src/org/openstreetmap/josm/io/session/SessionWriter.java
===================================================================
--- trunk/src/org/openstreetmap/josm/io/session/SessionWriter.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/io/session/SessionWriter.java	(revision 7033)
@@ -240,11 +240,9 @@
 
     public void write(File f) throws IOException {
-        OutputStream out = null;
-        try {
-            out = new FileOutputStream(f);
+        try (OutputStream out = new FileOutputStream(f)) {
+            write(out);
         } catch (FileNotFoundException e) {
             throw new IOException(e);
         }
-        write(out);
     }
 
@@ -262,5 +260,4 @@
             writeJos(doc, new BufferedOutputStream(out));
         }
-        Utils.close(out);
     }
 }
Index: trunk/src/org/openstreetmap/josm/plugins/Plugin.java
===================================================================
--- trunk/src/org/openstreetmap/josm/plugins/Plugin.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/plugins/Plugin.java	(revision 7033)
@@ -110,9 +110,8 @@
             pluginDir.mkdirs();
         }
-        FileOutputStream out = null;
-        InputStream in = null;
-        try {
-            out = new FileOutputStream(new File(pluginDirName, to));
-            in = getClass().getResourceAsStream(from);
+        try (
+            FileOutputStream out = new FileOutputStream(new File(pluginDirName, to));
+            InputStream in = getClass().getResourceAsStream(from)
+        ) {
             if (in == null) {
                 throw new IOException("Resource not found: "+from);
@@ -122,7 +121,4 @@
                 out.write(buffer, 0, len);
             }
-        } finally {
-            Utils.close(in);
-            Utils.close(out);
         }
     }
Index: trunk/src/org/openstreetmap/josm/plugins/PluginDownloadTask.java
===================================================================
--- trunk/src/org/openstreetmap/josm/plugins/PluginDownloadTask.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/plugins/PluginDownloadTask.java	(revision 7033)
@@ -24,5 +24,4 @@
 import org.openstreetmap.josm.io.MirroredInputStream;
 import org.openstreetmap.josm.tools.CheckParameterUtil;
-import org.openstreetmap.josm.tools.Utils;
 import org.xml.sax.SAXException;
 
@@ -118,6 +117,4 @@
                 throw new PluginDownloadException(tr("Download skipped"));
         }
-        OutputStream out = null;
-        InputStream in = null;
         try {
             if (pi.downloadlink == null) {
@@ -130,9 +127,12 @@
                 downloadConnection = MirroredInputStream.connectFollowingRedirect(url, PLUGIN_MIME_TYPES);
             }
-            in = downloadConnection.getInputStream();
-            out = new FileOutputStream(file);
-            byte[] buffer = new byte[8192];
-            for (int read = in.read(buffer); read != -1; read = in.read(buffer)) {
-                out.write(buffer, 0, read);
+            try (
+                InputStream in = downloadConnection.getInputStream();
+                OutputStream out = new FileOutputStream(file)
+            ) {
+                byte[] buffer = new byte[8192];
+                for (int read = in.read(buffer); read != -1; read = in.read(buffer)) {
+                    out.write(buffer, 0, read);
+                }
             }
         } catch (MalformedURLException e) {
@@ -145,9 +145,7 @@
             throw new PluginDownloadException(e);
         } finally {
-            Utils.close(in);
             synchronized(this) {
                 downloadConnection = null;
             }
-            Utils.close(out);
         }
     }
Index: trunk/src/org/openstreetmap/josm/plugins/PluginInformation.java
===================================================================
--- trunk/src/org/openstreetmap/josm/plugins/PluginInformation.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/plugins/PluginInformation.java	(revision 7033)
@@ -107,9 +107,8 @@
         this.name = name;
         this.file = file;
-        FileInputStream fis = null;
-        JarInputStream jar = null;
-        try {
-            fis = new FileInputStream(file);
-            jar = new JarInputStream(fis);
+        try (
+            FileInputStream fis = new FileInputStream(file);
+            JarInputStream jar = new JarInputStream(fis)
+        ) {
             Manifest manifest = jar.getManifest();
             if (manifest == null)
@@ -119,7 +118,4 @@
         } catch (IOException e) {
             throw new PluginException(name, e);
-        } finally {
-            Utils.close(jar);
-            Utils.close(fis);
         }
     }
@@ -380,7 +376,11 @@
         String name = pluginName;
         name = name.replaceAll("[-. ]", "");
-        InputStream manifestStream = PluginInformation.class.getResourceAsStream("/org/openstreetmap/josm/plugins/"+name+"/MANIFEST.MF");
-        if (manifestStream != null)
-            return new PluginInformation(manifestStream, pluginName, null);
+        try (InputStream manifestStream = PluginInformation.class.getResourceAsStream("/org/openstreetmap/josm/plugins/"+name+"/MANIFEST.MF")) {
+            if (manifestStream != null) {
+                return new PluginInformation(manifestStream, pluginName, null);
+            }
+        } catch (IOException e) {
+            Main.warn(e);
+        }
 
         Collection<String> locations = getPluginLocations();
Index: trunk/src/org/openstreetmap/josm/plugins/ReadLocalPluginInformationTask.java
===================================================================
--- trunk/src/org/openstreetmap/josm/plugins/ReadLocalPluginInformationTask.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/plugins/ReadLocalPluginInformationTask.java	(revision 7033)
@@ -172,7 +172,5 @@
 
     protected void processLocalPluginInformationFile(File file) throws PluginListParseException{
-        FileInputStream fin = null;
-        try {
-            fin = new FileInputStream(file);
+        try (FileInputStream fin = new FileInputStream(file)) {
             List<PluginInformation> pis = new PluginListParser().parse(fin);
             for (PluginInformation pi : pis) {
@@ -185,6 +183,4 @@
         } catch(IOException e) {
             throw new PluginListParseException(e);
-        } finally {
-            Utils.close(fin);
         }
     }
Index: trunk/src/org/openstreetmap/josm/plugins/ReadRemotePluginInformationTask.java
===================================================================
--- trunk/src/org/openstreetmap/josm/plugins/ReadRemotePluginInformationTask.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/plugins/ReadRemotePluginInformationTask.java	(revision 7033)
@@ -203,20 +203,23 @@
 
     private void handleIOException(final ProgressMonitor monitor, IOException e, final String title, final String firstMessage, boolean displayMsg) {
-        InputStream errStream = connection.getErrorStream();
         StringBuilder sb = new StringBuilder();
-        if (errStream != null) {
-            BufferedReader err = null;
-            try {
-                String line;
-                err = new BufferedReader(new InputStreamReader(errStream, Utils.UTF_8));
-                while ((line = err.readLine()) != null) {
-                    sb.append(line).append("\n");
-                }
-            } catch (Exception ex) {
-                Main.error(e);
-                Main.error(ex);
-            } finally {
-                Utils.close(err);
-            }
+        try (InputStream errStream = connection.getErrorStream()) {
+            if (errStream != null) {
+                BufferedReader err = null;
+                try {
+                    String line;
+                    err = new BufferedReader(new InputStreamReader(errStream, Utils.UTF_8));
+                    while ((line = err.readLine()) != null) {
+                        sb.append(line).append("\n");
+                    }
+                } catch (Exception ex) {
+                    Main.error(e);
+                    Main.error(ex);
+                } finally {
+                    Utils.close(err);
+                }
+            }
+        } catch (IOException ex) {
+            Main.warn(ex);
         }
         final String msg = e.getMessage();
@@ -265,6 +268,4 @@
      */
     protected void downloadPluginIcons(String site, File destFile, ProgressMonitor monitor) {
-        InputStream in = null;
-        OutputStream out = null;
         try {
             site = site.replaceAll("%<(.*)>", "");
@@ -278,9 +279,12 @@
                 connection.setRequestProperty("Cache-Control", "no-cache");
             }
-            in = connection.getInputStream();
-            out = new FileOutputStream(destFile);
-            byte[] buffer = new byte[8192];
-            for (int read = in.read(buffer); read != -1; read = in.read(buffer)) {
-                out.write(buffer, 0, read);
+            try (
+                InputStream in = connection.getInputStream();
+                OutputStream out = new FileOutputStream(destFile)
+            ) {
+                byte[] buffer = new byte[8192];
+                for (int read = in.read(buffer); read != -1; read = in.read(buffer)) {
+                    out.write(buffer, 0, read);
+                }
             }
         } catch (MalformedURLException e) {
@@ -293,5 +297,4 @@
             return;
         } finally {
-            Utils.close(out);
             synchronized(this) {
                 if (connection != null) {
@@ -300,5 +303,4 @@
                 connection = null;
             }
-            Utils.close(in);
             monitor.finishTask();
         }
@@ -321,22 +323,16 @@
      */
     protected void cachePluginList(String site, String list) {
-        PrintWriter writer = null;
-        try {
-            File pluginDir = Main.pref.getPluginsDirectory();
-            if (!pluginDir.exists() && !pluginDir.mkdirs()) {
-                Main.warn(tr("Failed to create plugin directory ''{0}''. Cannot cache plugin list from plugin site ''{1}''.", pluginDir.toString(), site));
-            }
-            File cacheFile = createSiteCacheFile(pluginDir, site, CacheType.PLUGIN_LIST);
-            getProgressMonitor().subTask(tr("Writing plugin list to local cache ''{0}''", cacheFile.toString()));
-            writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(cacheFile), Utils.UTF_8));
+        File pluginDir = Main.pref.getPluginsDirectory();
+        if (!pluginDir.exists() && !pluginDir.mkdirs()) {
+            Main.warn(tr("Failed to create plugin directory ''{0}''. Cannot cache plugin list from plugin site ''{1}''.", pluginDir.toString(), site));
+        }
+        File cacheFile = createSiteCacheFile(pluginDir, site, CacheType.PLUGIN_LIST);
+        getProgressMonitor().subTask(tr("Writing plugin list to local cache ''{0}''", cacheFile.toString()));
+        try (PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(cacheFile), Utils.UTF_8))) {
             writer.write(list);
+            writer.flush();
         } catch(IOException e) {
             // just failed to write the cache file. No big deal, but log the exception anyway
             Main.error(e);
-        } finally {
-            if (writer != null) {
-                writer.flush();
-                Utils.close(writer);
-            }
         }
     }
Index: trunk/src/org/openstreetmap/josm/tools/AudioUtil.java
===================================================================
--- trunk/src/org/openstreetmap/josm/tools/AudioUtil.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/tools/AudioUtil.java	(revision 7033)
@@ -31,7 +31,6 @@
      */
     public static double getCalibratedDuration(File wavFile) {
-        try {
-            AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(
-                new URL("file:".concat(wavFile.getAbsolutePath())));
+        try (AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(
+                new URL("file:".concat(wavFile.getAbsolutePath())))) {
             AudioFormat audioFormat = audioInputStream.getFormat();
             long filesize = wavFile.length();
Index: trunk/src/org/openstreetmap/josm/tools/I18n.java
===================================================================
--- trunk/src/org/openstreetmap/josm/tools/I18n.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/tools/I18n.java	(revision 7033)
@@ -397,43 +397,34 @@
         if ("en".equals(loadedCode))
             return;
-        FileInputStream fis = null;
-        JarInputStream jar = null;
-        FileInputStream fisTrans = null;
-        JarInputStream jarTrans = null;
         String enfile = "data/en.lang";
         String langfile = "data/"+loadedCode+".lang";
-        try
-        {
+        try (
+            FileInputStream fis = new FileInputStream(source);
+            JarInputStream jar = new JarInputStream(fis)
+        ) {
             ZipEntry e;
-            fis = new FileInputStream(source);
-            jar = new JarInputStream(fis);
             boolean found = false;
-            while(!found && (e = jar.getNextEntry()) != null)
-            {
+            while (!found && (e = jar.getNextEntry()) != null) {
                 String name = e.getName();
                 if(name.equals(enfile))
                     found = true;
             }
-            if(found)
-            {
-                fisTrans = new FileInputStream(source);
-                jarTrans = new JarInputStream(fisTrans);
-                found = false;
-                while(!found && (e = jarTrans.getNextEntry()) != null)
-                {
-                    String name = e.getName();
-                    if(name.equals(langfile))
-                        found = true;
+            if (found) {
+                try (
+                    FileInputStream fisTrans = new FileInputStream(source);
+                    JarInputStream jarTrans = new JarInputStream(fisTrans)
+                ) {
+                    found = false;
+                    while(!found && (e = jarTrans.getNextEntry()) != null) {
+                        String name = e.getName();
+                        if (name.equals(langfile))
+                            found = true;
+                    }
+                    if (found)
+                        load(jar, jarTrans, true);
                 }
-                if(found)
-                    load(jar, jarTrans, true);
-            }
-        } catch(IOException e) {
+            }
+        } catch (IOException e) {
             // Ignore
-        } finally {
-            Utils.close(jar);
-            Utils.close(fis);
-            Utils.close(jarTrans);
-            Utils.close(fisTrans);
         }
     }
@@ -460,9 +451,8 @@
                 return false;
         }
-        InputStream enStream = null;
-        InputStream trStream = null;
-        try {
-            enStream = en.openStream();
-            trStream = tr.openStream();
+        try (
+            InputStream enStream = en.openStream();
+            InputStream trStream = tr.openStream()
+        ) {
             if (load(enStream, trStream, false)) {
                 pluralMode = languages.get(l);
@@ -470,9 +460,6 @@
                 return true;
             }
-        } catch(IOException e) {
+        } catch (IOException e) {
             // Ignore exception
-        } finally {
-            Utils.close(trStream);
-            Utils.close(enStream);
         }
         return false;
Index: trunk/src/org/openstreetmap/josm/tools/ImageProvider.java
===================================================================
--- trunk/src/org/openstreetmap/josm/tools/ImageProvider.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/tools/ImageProvider.java	(revision 7033)
@@ -504,8 +504,6 @@
 
     private static ImageResource getIfAvailableHttp(String url, ImageType type) {
-        MirroredInputStream is = null;
-        try {
-            is = new MirroredInputStream(url,
-                    new File(Main.pref.getCacheDirectory(), "images").getPath());
+        try (MirroredInputStream is = new MirroredInputStream(url,
+                    new File(Main.pref.getCacheDirectory(), "images").getPath())) {
             switch (type) {
             case SVG:
@@ -526,6 +524,4 @@
         } catch (IOException e) {
             return null;
-        } finally {
-            Utils.close(is);
         }
     }
@@ -603,7 +599,5 @@
 
     private static ImageResource getIfAvailableZip(String fullName, File archive, String inArchiveDir, ImageType type) {
-        ZipFile zipFile = null;
-        try {
-            zipFile = new ZipFile(archive);
+        try (ZipFile zipFile = new ZipFile(archive)) {
             if (inArchiveDir == null || ".".equals(inArchiveDir)) {
                 inArchiveDir = "";
@@ -613,12 +607,9 @@
             String entryName = inArchiveDir + fullName;
             ZipEntry entry = zipFile.getEntry(entryName);
-            if(entry != null)
-            {
+            if (entry != null) {
                 int size = (int)entry.getSize();
                 int offs = 0;
                 byte[] buf = new byte[size];
-                InputStream is = null;
-                try {
-                    is = zipFile.getInputStream(entry);
+                try (InputStream is = zipFile.getInputStream(entry)) {
                     switch (type) {
                     case SVG:
@@ -641,14 +632,10 @@
                         return img == null ? null : new ImageResource(img);
                     default:
-                        throw new AssertionError();
+                        throw new AssertionError("Unknown ImageType: "+type);
                     }
-                } finally {
-                    Utils.close(is);
                 }
             }
         } catch (Exception e) {
             Main.warn(tr("Failed to handle zip file ''{0}''. Exception was: {1}", archive.getName(), e.toString()));
-        } finally {
-            Utils.close(zipFile);
         }
         return null;
@@ -785,8 +772,10 @@
             });
 
-            parser.parse(new InputSource(new MirroredInputStream(
+            try (InputStream is = new MirroredInputStream(
                     base + fn,
-                    new File(Main.pref.getPreferencesDir(), "images").toString()
-                    )));
+                    new File(Main.pref.getPreferencesDir(), "images").toString())
+            ) {
+                parser.parse(new InputSource(is));
+            }
         } catch (SAXReturnException r) {
             return r.getResult();
Index: trunk/src/org/openstreetmap/josm/tools/PlatformHookUnixoid.java
===================================================================
--- trunk/src/org/openstreetmap/josm/tools/PlatformHookUnixoid.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/tools/PlatformHookUnixoid.java	(revision 7033)
@@ -283,7 +283,5 @@
                 File file = new File(path);
                 if (file.exists()) {
-                    BufferedReader reader = null;
-                    try {
-                        reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), Utils.UTF_8));
+                    try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), Utils.UTF_8))) {
                         String id = null;
                         String release = null;
@@ -313,6 +311,4 @@
                     } catch (IOException e) {
                         // Ignore
-                    } finally {
-                        Utils.close(reader);
                     }
                 }
Index: trunk/src/org/openstreetmap/josm/tools/WikiReader.java
===================================================================
--- trunk/src/org/openstreetmap/josm/tools/WikiReader.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/tools/WikiReader.java	(revision 7033)
@@ -43,11 +43,8 @@
     public String read(String url) throws IOException {
         URL u = new URL(url);
-        BufferedReader in = Utils.openURLReader(u);
-        try {
+        try (BufferedReader in = Utils.openURLReader(u)) {
             if (url.startsWith(baseurl) && !url.endsWith("?format=txt"))
                 return readFromTrac(in, u);
             return readNormal(in);
-        } finally {
-            Utils.close(in);
         }
     }
@@ -84,15 +81,9 @@
 
     private String readLang(URL url) throws IOException {
-        BufferedReader in;
-        try {
-            in = Utils.openURLReader(url);
+        try (BufferedReader in = Utils.openURLReader(url)) {
+            return readFromTrac(in, url);
         } catch (IOException e) {
             Main.addNetworkError(url, Utils.getRootCause(e));
             throw e;
-        }
-        try {
-            return readFromTrac(in, url);
-        } finally {
-            Utils.close(in);
         }
     }
Index: trunk/src/org/openstreetmap/josm/tools/XmlObjectParser.java
===================================================================
--- trunk/src/org/openstreetmap/josm/tools/XmlObjectParser.java	(revision 7031)
+++ trunk/src/org/openstreetmap/josm/tools/XmlObjectParser.java	(revision 7033)
@@ -5,4 +5,5 @@
 
 import java.io.IOException;
+import java.io.InputStream;
 import java.io.Reader;
 import java.lang.reflect.Field;
@@ -17,4 +18,5 @@
 import java.util.Stack;
 
+import javax.xml.XMLConstants;
 import javax.xml.parsers.ParserConfigurationException;
 import javax.xml.parsers.SAXParser;
@@ -278,7 +280,7 @@
 
     public Iterable<Object> startWithValidation(final Reader in, String namespace, String schemaSource) throws SAXException {
-        try {
-            SchemaFactory factory =  SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
-            Schema schema = factory.newSchema(new StreamSource(new MirroredInputStream(schemaSource)));
+        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
+        try (InputStream mis = new MirroredInputStream(schemaSource)) {
+            Schema schema = factory.newSchema(new StreamSource(mis));
             ValidatorHandler validator = schema.newValidatorHandler();
             validator.setContentHandler(parser);
