7021209: convert lang, math, util to use try-with-resources
Reviewed-by: alanb, darcy, naoto
--- a/jdk/src/share/classes/java/lang/Package.java Tue Feb 22 12:01:35 2011 -0800
+++ b/jdk/src/share/classes/java/lang/Package.java Tue Feb 22 15:34:17 2011 -0800
@@ -576,12 +576,10 @@
* Returns the Manifest for the specified JAR file name.
*/
private static Manifest loadManifest(String fn) {
- try {
- FileInputStream fis = new FileInputStream(fn);
- JarInputStream jis = new JarInputStream(fis, false);
- Manifest man = jis.getManifest();
- jis.close();
- return man;
+ try (FileInputStream fis = new FileInputStream(fn);
+ JarInputStream jis = new JarInputStream(fis, false))
+ {
+ return jis.getManifest();
} catch (IOException e) {
return null;
}
--- a/jdk/src/share/classes/java/util/Currency.java Tue Feb 22 12:01:35 2011 -0800
+++ b/jdk/src/share/classes/java/util/Currency.java Tue Feb 22 15:34:17 2011 -0800
@@ -233,7 +233,9 @@
"currency.properties");
if (propFile.exists()) {
Properties props = new Properties();
- props.load(new FileReader(propFile));
+ try (FileReader fr = new FileReader(propFile)) {
+ props.load(fr);
+ }
Set<String> keys = props.stringPropertyNames();
Pattern propertiesPattern =
Pattern.compile("([A-Z]{3})\\s*,\\s*(\\d{3})\\s*,\\s*([0-3])");
--- a/jdk/src/share/classes/sun/util/calendar/LocalGregorianCalendar.java Tue Feb 22 12:01:35 2011 -0800
+++ b/jdk/src/share/classes/sun/util/calendar/LocalGregorianCalendar.java Tue Feb 22 15:34:17 2011 -0800
@@ -127,7 +127,9 @@
calendarProps = (Properties) AccessController.doPrivileged(new PrivilegedExceptionAction() {
public Object run() throws IOException {
Properties props = new Properties();
- props.load(new FileInputStream(fname));
+ try (FileInputStream fis = new FileInputStream(fname)) {
+ props.load(fis);
+ }
return props;
}
});
--- a/jdk/src/solaris/classes/java/util/prefs/FileSystemPreferences.java Tue Feb 22 12:01:35 2011 -0800
+++ b/jdk/src/solaris/classes/java/util/prefs/FileSystemPreferences.java Tue Feb 22 15:34:17 2011 -0800
@@ -571,9 +571,9 @@
long newLastSyncTime = 0;
try {
newLastSyncTime = prefsFile.lastModified();
- FileInputStream fis = new FileInputStream(prefsFile);
- XmlSupport.importMap(fis, m);
- fis.close();
+ try (FileInputStream fis = new FileInputStream(prefsFile)) {
+ XmlSupport.importMap(fis, m);
+ }
} catch(Exception e) {
if (e instanceof InvalidPreferencesFormatException) {
getLogger().warning("Invalid preferences format in "
@@ -618,9 +618,9 @@
if (!dir.exists() && !dir.mkdirs())
throw new BackingStoreException(dir +
" create failed.");
- FileOutputStream fos = new FileOutputStream(tmpFile);
- XmlSupport.exportMap(fos, prefsCache);
- fos.close();
+ try (FileOutputStream fos = new FileOutputStream(tmpFile)) {
+ XmlSupport.exportMap(fos, prefsCache);
+ }
if (!tmpFile.renameTo(prefsFile))
throw new BackingStoreException("Can't rename " +
tmpFile + " to " + prefsFile);
--- a/jdk/test/java/lang/Character/CheckScript.java Tue Feb 22 12:01:35 2011 -0800
+++ b/jdk/test/java/lang/Character/CheckScript.java Tue Feb 22 15:34:17 2011 -0800
@@ -12,40 +12,43 @@
public class CheckScript {
- public static void main(String[] args) throws Exception {
-
- BufferedReader sbfr = null;
+ static BufferedReader open(String[] args) throws FileNotFoundException {
if (args.length == 0) {
- sbfr = new BufferedReader(new FileReader(new File(System.getProperty("test.src", "."), "Scripts.txt")));
+ return new BufferedReader(new FileReader(new File(System.getProperty("test.src", "."), "Scripts.txt")));
} else if (args.length == 1) {
- sbfr = new BufferedReader(new FileReader(args[0]));
+ return new BufferedReader(new FileReader(args[0]));
} else {
System.out.println("java CharacterScript Scripts.txt");
throw new RuntimeException("Datafile name should be specified.");
}
+ }
+
+ public static void main(String[] args) throws Exception {
+
Matcher m = Pattern.compile("(\\p{XDigit}+)(?:\\.{2}(\\p{XDigit}+))?\\s+;\\s+(\\w+)\\s+#.*").matcher("");
String line = null;
HashMap<String,ArrayList<Integer>> scripts = new HashMap<>();
- while ((line = sbfr.readLine()) != null) {
- if (line.length() <= 1 || line.charAt(0) == '#') {
- continue;
- }
- m.reset(line);
- if (m.matches()) {
- int start = Integer.parseInt(m.group(1), 16);
- int end = (m.group(2)==null)?start
- :Integer.parseInt(m.group(2), 16);
- String name = m.group(3).toLowerCase(Locale.ENGLISH);
- ArrayList<Integer> ranges = scripts.get(name);
- if (ranges == null) {
- ranges = new ArrayList<Integer>();
- scripts.put(name, ranges);
+ try (BufferedReader sbfr = open(args)) {
+ while ((line = sbfr.readLine()) != null) {
+ if (line.length() <= 1 || line.charAt(0) == '#') {
+ continue;
}
- ranges.add(start);
- ranges.add(end);
+ m.reset(line);
+ if (m.matches()) {
+ int start = Integer.parseInt(m.group(1), 16);
+ int end = (m.group(2)==null)?start
+ :Integer.parseInt(m.group(2), 16);
+ String name = m.group(3).toLowerCase(Locale.ENGLISH);
+ ArrayList<Integer> ranges = scripts.get(name);
+ if (ranges == null) {
+ ranges = new ArrayList<Integer>();
+ scripts.put(name, ranges);
+ }
+ ranges.add(start);
+ ranges.add(end);
+ }
}
}
- sbfr.close();
// check all defined ranges
Integer[] ZEROSIZEARRAY = new Integer[0];
for (String name : scripts.keySet()) {
--- a/jdk/test/java/lang/Runtime/shutdown/ShutdownHooks.java Tue Feb 22 12:01:35 2011 -0800
+++ b/jdk/test/java/lang/Runtime/shutdown/ShutdownHooks.java Tue Feb 22 15:34:17 2011 -0800
@@ -43,9 +43,9 @@
file = new File(dir, args[1]);
// write to file
System.out.println("writing to "+ file);
- PrintWriter pw = new PrintWriter(file);
- pw.println("Shutdown begins");
- pw.close();
+ try (PrintWriter pw = new PrintWriter(file)) {
+ pw.println("Shutdown begins");
+ }
}
public static class Cleaner extends Thread {
@@ -56,10 +56,8 @@
// register the DeleteOnExitHook while the application
// shutdown hook is running
file.deleteOnExit();
- try {
- PrintWriter pw = new PrintWriter(file);
+ try (PrintWriter pw = new PrintWriter(file)) {
pw.println("file is being deleted");
- pw.close();
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
--- a/jdk/test/java/lang/instrument/BootClassPath/Setup.java Tue Feb 22 12:01:35 2011 -0800
+++ b/jdk/test/java/lang/instrument/BootClassPath/Setup.java Tue Feb 22 15:34:17 2011 -0800
@@ -62,31 +62,33 @@
* Create manifest file with Boot-Class-Path encoding the
* sub-directory name.
*/
- FileOutputStream out = new FileOutputStream(manifestFile);
- out.write("Manifest-Version: 1.0\n".getBytes("UTF-8"));
+ try (FileOutputStream out = new FileOutputStream(manifestFile)) {
+ out.write("Manifest-Version: 1.0\n".getBytes("UTF-8"));
- byte[] premainBytes = ("Premain-Class: " + premainClass + "\n").getBytes("UTF-8");
- out.write(premainBytes);
+ byte[] premainBytes =
+ ("Premain-Class: " + premainClass + "\n").getBytes("UTF-8");
+ out.write(premainBytes);
- out.write( "Boot-Class-Path: ".getBytes("UTF-8") );
+ out.write( "Boot-Class-Path: ".getBytes("UTF-8") );
- byte[] value = bootClassPath.getBytes("UTF-8");
- for (int i=0; i<value.length; i++) {
- int v = (int)value[i];
- if (v < 0) v += 256;
- byte[] escaped = ("%" + Integer.toHexString(v)).getBytes("UTF-8");
- out.write(escaped);
+ byte[] value = bootClassPath.getBytes("UTF-8");
+ for (int i=0; i<value.length; i++) {
+ int v = (int)value[i];
+ if (v < 0) v += 256;
+ byte[] escaped =
+ ("%" + Integer.toHexString(v)).getBytes("UTF-8");
+ out.write(escaped);
+ }
+ out.write( "\n\n".getBytes("UTF-8") );
}
- out.write( "\n\n".getBytes("UTF-8") );
- out.close();
/*
* Write the name of the boot dir to "boot.dir"
*/
f = new File(workDir + fileSeparator + "boot.dir");
- out = new FileOutputStream(f);
- out.write(bootDir.getBytes(defaultEncoding));
- out.close();
+ try (FileOutputStream out = new FileOutputStream(f)) {
+ out.write(bootDir.getBytes(defaultEncoding));
+ }
}
/* ported from test/sun/tools/launcher/UnicodeTest.java */
--- a/jdk/test/java/lang/instrument/ilib/Inject.java Tue Feb 22 12:01:35 2011 -0800
+++ b/jdk/test/java/lang/instrument/ilib/Inject.java Tue Feb 22 15:34:17 2011 -0800
@@ -118,23 +118,24 @@
}
void dump(File outDir, String filename) throws IOException {
- FileOutputStream fileOut = new FileOutputStream(new File(outDir, filename));
- DataOutputStream dataOut = new DataOutputStream(fileOut);
-
- String currentClassName = null;
+ try (FileOutputStream fileOut =
+ new FileOutputStream(new File(outDir, filename));
+ DataOutputStream dataOut = new DataOutputStream(fileOut))
+ {
+ String currentClassName = null;
- dataOut.writeInt(infoList.size());
- for (Iterator<Info> it = infoList.iterator(); it.hasNext(); ) {
- Info info = it.next();
- if (!info.className.equals(currentClassName)) {
- dataOut.writeInt(123456); // class name marker
- currentClassName = info.className;
- dataOut.writeUTF(currentClassName);
+ dataOut.writeInt(infoList.size());
+ for (Iterator<Info> it = infoList.iterator(); it.hasNext(); ) {
+ Info info = it.next();
+ if (!info.className.equals(currentClassName)) {
+ dataOut.writeInt(123456); // class name marker
+ currentClassName = info.className;
+ dataOut.writeUTF(currentClassName);
+ }
+ dataOut.writeInt(info.location);
+ dataOut.writeUTF(info.methodName);
}
- dataOut.writeInt(info.location);
- dataOut.writeUTF(info.methodName);
}
- dataOut.close();
}
public byte[] bytecodes(String className, String methodName, int location) {
--- a/jdk/test/java/math/BigInteger/BigIntegerTest.java Tue Feb 22 12:01:35 2011 -0800
+++ b/jdk/test/java/math/BigInteger/BigIntegerTest.java Tue Feb 22 15:34:17 2011 -0800
@@ -645,26 +645,17 @@
BigInteger b2 = null;
File f = new File("serialtest");
- FileOutputStream fos = new FileOutputStream(f);
- try {
- ObjectOutputStream oos = new ObjectOutputStream(fos);
- try {
+
+ try (FileOutputStream fos = new FileOutputStream(f)) {
+ try (ObjectOutputStream oos = new ObjectOutputStream(fos)) {
oos.writeObject(b1);
oos.flush();
- } finally {
- oos.close();
}
- FileInputStream fis = new FileInputStream(f);
- try {
- ObjectInputStream ois = new ObjectInputStream(fis);
- try {
- b2 = (BigInteger)ois.readObject();
- } finally {
- ois.close();
- }
- } finally {
- fis.close();
+ try (FileInputStream fis = new FileInputStream(f);
+ ObjectInputStream ois = new ObjectInputStream(fis))
+ {
+ b2 = (BigInteger)ois.readObject();
}
if (!b1.equals(b2) ||
@@ -673,8 +664,6 @@
System.err.println("Serialized failed for hex " +
b1.toString(16));
}
- } finally {
- fos.close();
}
f.delete();
}
@@ -683,29 +672,17 @@
BigInteger b1 = fetchNumber(rnd.nextInt(100));
BigInteger b2 = null;
File f = new File("serialtest");
- FileOutputStream fos = new FileOutputStream(f);
- try {
- ObjectOutputStream oos = new ObjectOutputStream(fos);
- try {
+ try (FileOutputStream fos = new FileOutputStream(f)) {
+ try (ObjectOutputStream oos = new ObjectOutputStream(fos)) {
oos.writeObject(b1);
oos.flush();
- } finally {
- oos.close();
}
- FileInputStream fis = new FileInputStream(f);
- try {
- ObjectInputStream ois = new ObjectInputStream(fis);
- try {
- b2 = (BigInteger)ois.readObject();
- } finally {
- ois.close();
- }
- } finally {
- fis.close();
+ try (FileInputStream fis = new FileInputStream(f);
+ ObjectInputStream ois = new ObjectInputStream(fis))
+ {
+ b2 = (BigInteger)ois.readObject();
}
- } finally {
- fos.close();
}
if (!b1.equals(b2) ||
--- a/jdk/test/java/util/Currency/ValidateISO4217.java Tue Feb 22 12:01:35 2011 -0800
+++ b/jdk/test/java/util/Currency/ValidateISO4217.java Tue Feb 22 15:34:17 2011 -0800
@@ -111,57 +111,58 @@
static void test1() throws Exception {
- FileReader fr = new FileReader(new File(System.getProperty("test.src", "."), datafile));
- BufferedReader in = new BufferedReader(fr);
- String line;
- SimpleDateFormat format = null;
+ try (FileReader fr = new FileReader(new File(System.getProperty("test.src", "."), datafile));
+ BufferedReader in = new BufferedReader(fr))
+ {
+ String line;
+ SimpleDateFormat format = null;
- while ((line = in.readLine()) != null) {
- if (line.length() == 0 || line.charAt(0) == '#') {
- continue;
- }
+ while ((line = in.readLine()) != null) {
+ if (line.length() == 0 || line.charAt(0) == '#') {
+ continue;
+ }
- StringTokenizer tokens = new StringTokenizer(line, "\t");
- String country = tokens.nextToken();
- if (country.length() != 2) {
- continue;
- }
+ StringTokenizer tokens = new StringTokenizer(line, "\t");
+ String country = tokens.nextToken();
+ if (country.length() != 2) {
+ continue;
+ }
- String currency;
- String numeric;
- String minorUnit;
- int tokensCount = tokens.countTokens();
- if (tokensCount < 3) {
- currency = "";
- numeric = "0";
- minorUnit = "0";
- } else {
- currency = tokens.nextToken();
- numeric = tokens.nextToken();
- minorUnit = tokens.nextToken();
- testCurrencies.add(Currency.getInstance(currency));
+ String currency;
+ String numeric;
+ String minorUnit;
+ int tokensCount = tokens.countTokens();
+ if (tokensCount < 3) {
+ currency = "";
+ numeric = "0";
+ minorUnit = "0";
+ } else {
+ currency = tokens.nextToken();
+ numeric = tokens.nextToken();
+ minorUnit = tokens.nextToken();
+ testCurrencies.add(Currency.getInstance(currency));
- // check for the cutover
- if (tokensCount > 3) {
- if (format == null) {
- format = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss", Locale.US);
- format.setTimeZone(TimeZone.getTimeZone("GMT"));
- format.setLenient(false);
- }
- if (format.parse(tokens.nextToken()).getTime() <
- System.currentTimeMillis()) {
- currency = tokens.nextToken();
- numeric = tokens.nextToken();
- minorUnit = tokens.nextToken();
- testCurrencies.add(Currency.getInstance(currency));
+ // check for the cutover
+ if (tokensCount > 3) {
+ if (format == null) {
+ format = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss", Locale.US);
+ format.setTimeZone(TimeZone.getTimeZone("GMT"));
+ format.setLenient(false);
+ }
+ if (format.parse(tokens.nextToken()).getTime() <
+ System.currentTimeMillis()) {
+ currency = tokens.nextToken();
+ numeric = tokens.nextToken();
+ minorUnit = tokens.nextToken();
+ testCurrencies.add(Currency.getInstance(currency));
+ }
}
}
+ int index = toIndex(country);
+ testCountryCurrency(country, currency, Integer.parseInt(numeric),
+ Integer.parseInt(minorUnit), index);
}
- int index = toIndex(country);
- testCountryCurrency(country, currency, Integer.parseInt(numeric),
- Integer.parseInt(minorUnit), index);
}
- in.close();
for (int i = 0; i < additionalCodes.length; i++) {
int index = toIndex(additionalCodes[i][0]);
--- a/jdk/test/java/util/Formatter/FailingConstructors.java Tue Feb 22 12:01:35 2011 -0800
+++ b/jdk/test/java/util/Formatter/FailingConstructors.java Tue Feb 22 15:34:17 2011 -0800
@@ -34,6 +34,7 @@
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
+import java.nio.file.Files;
import java.util.Formatter;
public class FailingConstructors {
@@ -47,9 +48,7 @@
/* create the file and write its contents */
File file = File.createTempFile(fileName, null);
file.deleteOnExit();
- FileOutputStream fos = new FileOutputStream(file);
- fos.write(FILE_CONTENTS.getBytes());
- fos.close();
+ Files.write(file.toPath(), FILE_CONTENTS.getBytes());
test(true, file);
file.delete();
--- a/jdk/test/java/util/Locale/LocaleEnhanceTest.java Tue Feb 22 12:01:35 2011 -0800
+++ b/jdk/test/java/util/Locale/LocaleEnhanceTest.java Tue Feb 22 15:34:17 2011 -0800
@@ -1187,14 +1187,12 @@
locale = new Locale(lang, country, variant);
}
- // desrialize
- try {
- FileInputStream fis = new FileInputStream(testfile);
- ObjectInputStream ois = new ObjectInputStream(fis);
-
+ // deserialize
+ try (FileInputStream fis = new FileInputStream(testfile);
+ ObjectInputStream ois = new ObjectInputStream(fis))
+ {
Object o = ois.readObject();
assertEquals("Deserialize Java 6 Locale " + locale, o, locale);
- ois.close();
} catch (Exception e) {
errln("Exception while reading " + testfile.getAbsolutePath() + " - " + e.getMessage());
}
--- a/jdk/test/java/util/ResourceBundle/Bug6204853.java Tue Feb 22 12:01:35 2011 -0800
+++ b/jdk/test/java/util/ResourceBundle/Bug6204853.java Tue Feb 22 15:34:17 2011 -0800
@@ -39,24 +39,19 @@
public final class Bug6204853 {
public Bug6204853() {
- try {
- String srcDir = System.getProperty("test.src", ".");
- FileInputStream fis8859_1 =
- new FileInputStream(new File(srcDir, "Bug6204853.properties"));
- FileInputStream fisUtf8 =
- new FileInputStream(new File(srcDir, "Bug6204853_Utf8.properties"));
- InputStreamReader isrUtf8 = new InputStreamReader(fisUtf8, "UTF-8");
-
+ String srcDir = System.getProperty("test.src", ".");
+ try (FileInputStream fis8859_1 =
+ new FileInputStream(new File(srcDir, "Bug6204853.properties"));
+ FileInputStream fisUtf8 =
+ new FileInputStream(new File(srcDir, "Bug6204853_Utf8.properties"));
+ InputStreamReader isrUtf8 = new InputStreamReader(fisUtf8, "UTF-8"))
+ {
PropertyResourceBundle bundleUtf8 = new PropertyResourceBundle(isrUtf8);
PropertyResourceBundle bundle = new PropertyResourceBundle(fis8859_1);
String[] arrayUtf8 = createKeyValueArray(bundleUtf8);
String[] array = createKeyValueArray(bundle);
- isrUtf8.close();
- fisUtf8.close();
- fis8859_1.close();
-
if (!Arrays.equals(arrayUtf8, array)) {
throw new RuntimeException("PropertyResourceBundle constructed from a UTF-8 encoded property file is not equal to the one constructed from ISO-8859-1 encoded property file.");
}
--- a/jdk/test/java/util/Scanner/FailingConstructors.java Tue Feb 22 12:01:35 2011 -0800
+++ b/jdk/test/java/util/Scanner/FailingConstructors.java Tue Feb 22 15:34:17 2011 -0800
@@ -33,6 +33,7 @@
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
+import java.nio.file.Files;
import java.util.Scanner;
public class FailingConstructors {
@@ -46,9 +47,7 @@
/* create the file and write its contents */
File file = File.createTempFile(fileName, null);
file.deleteOnExit();
- FileOutputStream fos = new FileOutputStream(file);
- fos.write(FILE_CONTENTS.getBytes());
- fos.close();
+ Files.write(file.toPath(), FILE_CONTENTS.getBytes());
test(true, file);
file.delete();