提交 8e122c39 编写于 作者: S smarks

7021209: convert lang, math, util to use try-with-resources

Reviewed-by: alanb, darcy, naoto
上级 d3fcac4b
...@@ -576,12 +576,10 @@ public class Package implements java.lang.reflect.AnnotatedElement { ...@@ -576,12 +576,10 @@ public class Package implements java.lang.reflect.AnnotatedElement {
* Returns the Manifest for the specified JAR file name. * Returns the Manifest for the specified JAR file name.
*/ */
private static Manifest loadManifest(String fn) { private static Manifest loadManifest(String fn) {
try { try (FileInputStream fis = new FileInputStream(fn);
FileInputStream fis = new FileInputStream(fn); JarInputStream jis = new JarInputStream(fis, false))
JarInputStream jis = new JarInputStream(fis, false); {
Manifest man = jis.getManifest(); return jis.getManifest();
jis.close();
return man;
} catch (IOException e) { } catch (IOException e) {
return null; return null;
} }
......
...@@ -233,7 +233,9 @@ public final class Currency implements Serializable { ...@@ -233,7 +233,9 @@ public final class Currency implements Serializable {
"currency.properties"); "currency.properties");
if (propFile.exists()) { if (propFile.exists()) {
Properties props = new Properties(); Properties props = new Properties();
props.load(new FileReader(propFile)); try (FileReader fr = new FileReader(propFile)) {
props.load(fr);
}
Set<String> keys = props.stringPropertyNames(); Set<String> keys = props.stringPropertyNames();
Pattern propertiesPattern = Pattern propertiesPattern =
Pattern.compile("([A-Z]{3})\\s*,\\s*(\\d{3})\\s*,\\s*([0-3])"); Pattern.compile("([A-Z]{3})\\s*,\\s*(\\d{3})\\s*,\\s*([0-3])");
......
...@@ -127,7 +127,9 @@ public class LocalGregorianCalendar extends BaseCalendar { ...@@ -127,7 +127,9 @@ public class LocalGregorianCalendar extends BaseCalendar {
calendarProps = (Properties) AccessController.doPrivileged(new PrivilegedExceptionAction() { calendarProps = (Properties) AccessController.doPrivileged(new PrivilegedExceptionAction() {
public Object run() throws IOException { public Object run() throws IOException {
Properties props = new Properties(); Properties props = new Properties();
props.load(new FileInputStream(fname)); try (FileInputStream fis = new FileInputStream(fname)) {
props.load(fis);
}
return props; return props;
} }
}); });
......
...@@ -571,9 +571,9 @@ class FileSystemPreferences extends AbstractPreferences { ...@@ -571,9 +571,9 @@ class FileSystemPreferences extends AbstractPreferences {
long newLastSyncTime = 0; long newLastSyncTime = 0;
try { try {
newLastSyncTime = prefsFile.lastModified(); newLastSyncTime = prefsFile.lastModified();
FileInputStream fis = new FileInputStream(prefsFile); try (FileInputStream fis = new FileInputStream(prefsFile)) {
XmlSupport.importMap(fis, m); XmlSupport.importMap(fis, m);
fis.close(); }
} catch(Exception e) { } catch(Exception e) {
if (e instanceof InvalidPreferencesFormatException) { if (e instanceof InvalidPreferencesFormatException) {
getLogger().warning("Invalid preferences format in " getLogger().warning("Invalid preferences format in "
...@@ -618,9 +618,9 @@ class FileSystemPreferences extends AbstractPreferences { ...@@ -618,9 +618,9 @@ class FileSystemPreferences extends AbstractPreferences {
if (!dir.exists() && !dir.mkdirs()) if (!dir.exists() && !dir.mkdirs())
throw new BackingStoreException(dir + throw new BackingStoreException(dir +
" create failed."); " create failed.");
FileOutputStream fos = new FileOutputStream(tmpFile); try (FileOutputStream fos = new FileOutputStream(tmpFile)) {
XmlSupport.exportMap(fos, prefsCache); XmlSupport.exportMap(fos, prefsCache);
fos.close(); }
if (!tmpFile.renameTo(prefsFile)) if (!tmpFile.renameTo(prefsFile))
throw new BackingStoreException("Can't rename " + throw new BackingStoreException("Can't rename " +
tmpFile + " to " + prefsFile); tmpFile + " to " + prefsFile);
......
...@@ -12,20 +12,23 @@ import java.lang.Character.UnicodeScript; ...@@ -12,20 +12,23 @@ import java.lang.Character.UnicodeScript;
public class CheckScript { public class CheckScript {
public static void main(String[] args) throws Exception { static BufferedReader open(String[] args) throws FileNotFoundException {
BufferedReader sbfr = null;
if (args.length == 0) { 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) { } else if (args.length == 1) {
sbfr = new BufferedReader(new FileReader(args[0])); return new BufferedReader(new FileReader(args[0]));
} else { } else {
System.out.println("java CharacterScript Scripts.txt"); System.out.println("java CharacterScript Scripts.txt");
throw new RuntimeException("Datafile name should be specified."); 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(""); Matcher m = Pattern.compile("(\\p{XDigit}+)(?:\\.{2}(\\p{XDigit}+))?\\s+;\\s+(\\w+)\\s+#.*").matcher("");
String line = null; String line = null;
HashMap<String,ArrayList<Integer>> scripts = new HashMap<>(); HashMap<String,ArrayList<Integer>> scripts = new HashMap<>();
try (BufferedReader sbfr = open(args)) {
while ((line = sbfr.readLine()) != null) { while ((line = sbfr.readLine()) != null) {
if (line.length() <= 1 || line.charAt(0) == '#') { if (line.length() <= 1 || line.charAt(0) == '#') {
continue; continue;
...@@ -45,7 +48,7 @@ public class CheckScript { ...@@ -45,7 +48,7 @@ public class CheckScript {
ranges.add(end); ranges.add(end);
} }
} }
sbfr.close(); }
// check all defined ranges // check all defined ranges
Integer[] ZEROSIZEARRAY = new Integer[0]; Integer[] ZEROSIZEARRAY = new Integer[0];
for (String name : scripts.keySet()) { for (String name : scripts.keySet()) {
......
...@@ -43,9 +43,9 @@ public class ShutdownHooks { ...@@ -43,9 +43,9 @@ public class ShutdownHooks {
file = new File(dir, args[1]); file = new File(dir, args[1]);
// write to file // write to file
System.out.println("writing to "+ file); System.out.println("writing to "+ file);
PrintWriter pw = new PrintWriter(file); try (PrintWriter pw = new PrintWriter(file)) {
pw.println("Shutdown begins"); pw.println("Shutdown begins");
pw.close(); }
} }
public static class Cleaner extends Thread { public static class Cleaner extends Thread {
...@@ -56,10 +56,8 @@ public class ShutdownHooks { ...@@ -56,10 +56,8 @@ public class ShutdownHooks {
// register the DeleteOnExitHook while the application // register the DeleteOnExitHook while the application
// shutdown hook is running // shutdown hook is running
file.deleteOnExit(); file.deleteOnExit();
try { try (PrintWriter pw = new PrintWriter(file)) {
PrintWriter pw = new PrintWriter(file);
pw.println("file is being deleted"); pw.println("file is being deleted");
pw.close();
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
......
...@@ -62,10 +62,11 @@ public class Setup { ...@@ -62,10 +62,11 @@ public class Setup {
* Create manifest file with Boot-Class-Path encoding the * Create manifest file with Boot-Class-Path encoding the
* sub-directory name. * sub-directory name.
*/ */
FileOutputStream out = new FileOutputStream(manifestFile); try (FileOutputStream out = new FileOutputStream(manifestFile)) {
out.write("Manifest-Version: 1.0\n".getBytes("UTF-8")); out.write("Manifest-Version: 1.0\n".getBytes("UTF-8"));
byte[] premainBytes = ("Premain-Class: " + premainClass + "\n").getBytes("UTF-8"); byte[] premainBytes =
("Premain-Class: " + premainClass + "\n").getBytes("UTF-8");
out.write(premainBytes); out.write(premainBytes);
out.write( "Boot-Class-Path: ".getBytes("UTF-8") ); out.write( "Boot-Class-Path: ".getBytes("UTF-8") );
...@@ -74,19 +75,20 @@ public class Setup { ...@@ -74,19 +75,20 @@ public class Setup {
for (int i=0; i<value.length; i++) { for (int i=0; i<value.length; i++) {
int v = (int)value[i]; int v = (int)value[i];
if (v < 0) v += 256; if (v < 0) v += 256;
byte[] escaped = ("%" + Integer.toHexString(v)).getBytes("UTF-8"); byte[] escaped =
("%" + Integer.toHexString(v)).getBytes("UTF-8");
out.write(escaped); 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" * Write the name of the boot dir to "boot.dir"
*/ */
f = new File(workDir + fileSeparator + "boot.dir"); f = new File(workDir + fileSeparator + "boot.dir");
out = new FileOutputStream(f); try (FileOutputStream out = new FileOutputStream(f)) {
out.write(bootDir.getBytes(defaultEncoding)); out.write(bootDir.getBytes(defaultEncoding));
out.close(); }
} }
/* ported from test/sun/tools/launcher/UnicodeTest.java */ /* ported from test/sun/tools/launcher/UnicodeTest.java */
......
...@@ -118,9 +118,10 @@ public class Inject implements RuntimeConstants { ...@@ -118,9 +118,10 @@ public class Inject implements RuntimeConstants {
} }
void dump(File outDir, String filename) throws IOException { void dump(File outDir, String filename) throws IOException {
FileOutputStream fileOut = new FileOutputStream(new File(outDir, filename)); try (FileOutputStream fileOut =
DataOutputStream dataOut = new DataOutputStream(fileOut); new FileOutputStream(new File(outDir, filename));
DataOutputStream dataOut = new DataOutputStream(fileOut))
{
String currentClassName = null; String currentClassName = null;
dataOut.writeInt(infoList.size()); dataOut.writeInt(infoList.size());
...@@ -134,7 +135,7 @@ public class Inject implements RuntimeConstants { ...@@ -134,7 +135,7 @@ public class Inject implements RuntimeConstants {
dataOut.writeInt(info.location); dataOut.writeInt(info.location);
dataOut.writeUTF(info.methodName); dataOut.writeUTF(info.methodName);
} }
dataOut.close(); }
} }
public byte[] bytecodes(String className, String methodName, int location) { public byte[] bytecodes(String className, String methodName, int location) {
......
...@@ -645,26 +645,17 @@ public class BigIntegerTest { ...@@ -645,26 +645,17 @@ public class BigIntegerTest {
BigInteger b2 = null; BigInteger b2 = null;
File f = new File("serialtest"); File f = new File("serialtest");
FileOutputStream fos = new FileOutputStream(f);
try { try (FileOutputStream fos = new FileOutputStream(f)) {
ObjectOutputStream oos = new ObjectOutputStream(fos); try (ObjectOutputStream oos = new ObjectOutputStream(fos)) {
try {
oos.writeObject(b1); oos.writeObject(b1);
oos.flush(); oos.flush();
} finally {
oos.close();
} }
FileInputStream fis = new FileInputStream(f); try (FileInputStream fis = new FileInputStream(f);
try { ObjectInputStream ois = new ObjectInputStream(fis))
ObjectInputStream ois = new ObjectInputStream(fis); {
try {
b2 = (BigInteger)ois.readObject(); b2 = (BigInteger)ois.readObject();
} finally {
ois.close();
}
} finally {
fis.close();
} }
if (!b1.equals(b2) || if (!b1.equals(b2) ||
...@@ -673,8 +664,6 @@ public class BigIntegerTest { ...@@ -673,8 +664,6 @@ public class BigIntegerTest {
System.err.println("Serialized failed for hex " + System.err.println("Serialized failed for hex " +
b1.toString(16)); b1.toString(16));
} }
} finally {
fos.close();
} }
f.delete(); f.delete();
} }
...@@ -683,29 +672,17 @@ public class BigIntegerTest { ...@@ -683,29 +672,17 @@ public class BigIntegerTest {
BigInteger b1 = fetchNumber(rnd.nextInt(100)); BigInteger b1 = fetchNumber(rnd.nextInt(100));
BigInteger b2 = null; BigInteger b2 = null;
File f = new File("serialtest"); File f = new File("serialtest");
FileOutputStream fos = new FileOutputStream(f); try (FileOutputStream fos = new FileOutputStream(f)) {
try { try (ObjectOutputStream oos = new ObjectOutputStream(fos)) {
ObjectOutputStream oos = new ObjectOutputStream(fos);
try {
oos.writeObject(b1); oos.writeObject(b1);
oos.flush(); oos.flush();
} finally {
oos.close();
} }
FileInputStream fis = new FileInputStream(f); try (FileInputStream fis = new FileInputStream(f);
try { ObjectInputStream ois = new ObjectInputStream(fis))
ObjectInputStream ois = new ObjectInputStream(fis); {
try {
b2 = (BigInteger)ois.readObject(); b2 = (BigInteger)ois.readObject();
} finally {
ois.close();
}
} finally {
fis.close();
} }
} finally {
fos.close();
} }
if (!b1.equals(b2) || if (!b1.equals(b2) ||
......
...@@ -111,8 +111,9 @@ public class ValidateISO4217 { ...@@ -111,8 +111,9 @@ public class ValidateISO4217 {
static void test1() throws Exception { static void test1() throws Exception {
FileReader fr = new FileReader(new File(System.getProperty("test.src", "."), datafile)); try (FileReader fr = new FileReader(new File(System.getProperty("test.src", "."), datafile));
BufferedReader in = new BufferedReader(fr); BufferedReader in = new BufferedReader(fr))
{
String line; String line;
SimpleDateFormat format = null; SimpleDateFormat format = null;
...@@ -161,7 +162,7 @@ public class ValidateISO4217 { ...@@ -161,7 +162,7 @@ public class ValidateISO4217 {
testCountryCurrency(country, currency, Integer.parseInt(numeric), testCountryCurrency(country, currency, Integer.parseInt(numeric),
Integer.parseInt(minorUnit), index); Integer.parseInt(minorUnit), index);
} }
in.close(); }
for (int i = 0; i < additionalCodes.length; i++) { for (int i = 0; i < additionalCodes.length; i++) {
int index = toIndex(additionalCodes[i][0]); int index = toIndex(additionalCodes[i][0]);
......
...@@ -34,6 +34,7 @@ import java.io.FileOutputStream; ...@@ -34,6 +34,7 @@ import java.io.FileOutputStream;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.nio.file.Files;
import java.util.Formatter; import java.util.Formatter;
public class FailingConstructors { public class FailingConstructors {
...@@ -47,9 +48,7 @@ public class FailingConstructors { ...@@ -47,9 +48,7 @@ public class FailingConstructors {
/* create the file and write its contents */ /* create the file and write its contents */
File file = File.createTempFile(fileName, null); File file = File.createTempFile(fileName, null);
file.deleteOnExit(); file.deleteOnExit();
FileOutputStream fos = new FileOutputStream(file); Files.write(file.toPath(), FILE_CONTENTS.getBytes());
fos.write(FILE_CONTENTS.getBytes());
fos.close();
test(true, file); test(true, file);
file.delete(); file.delete();
......
...@@ -1187,14 +1187,12 @@ public class LocaleEnhanceTest extends LocaleTestFmwk { ...@@ -1187,14 +1187,12 @@ public class LocaleEnhanceTest extends LocaleTestFmwk {
locale = new Locale(lang, country, variant); locale = new Locale(lang, country, variant);
} }
// desrialize // deserialize
try { try (FileInputStream fis = new FileInputStream(testfile);
FileInputStream fis = new FileInputStream(testfile); ObjectInputStream ois = new ObjectInputStream(fis))
ObjectInputStream ois = new ObjectInputStream(fis); {
Object o = ois.readObject(); Object o = ois.readObject();
assertEquals("Deserialize Java 6 Locale " + locale, o, locale); assertEquals("Deserialize Java 6 Locale " + locale, o, locale);
ois.close();
} catch (Exception e) { } catch (Exception e) {
errln("Exception while reading " + testfile.getAbsolutePath() + " - " + e.getMessage()); errln("Exception while reading " + testfile.getAbsolutePath() + " - " + e.getMessage());
} }
......
...@@ -39,24 +39,19 @@ import java.util.PropertyResourceBundle; ...@@ -39,24 +39,19 @@ import java.util.PropertyResourceBundle;
public final class Bug6204853 { public final class Bug6204853 {
public Bug6204853() { public Bug6204853() {
try {
String srcDir = System.getProperty("test.src", "."); String srcDir = System.getProperty("test.src", ".");
FileInputStream fis8859_1 = try (FileInputStream fis8859_1 =
new FileInputStream(new File(srcDir, "Bug6204853.properties")); new FileInputStream(new File(srcDir, "Bug6204853.properties"));
FileInputStream fisUtf8 = FileInputStream fisUtf8 =
new FileInputStream(new File(srcDir, "Bug6204853_Utf8.properties")); new FileInputStream(new File(srcDir, "Bug6204853_Utf8.properties"));
InputStreamReader isrUtf8 = new InputStreamReader(fisUtf8, "UTF-8"); InputStreamReader isrUtf8 = new InputStreamReader(fisUtf8, "UTF-8"))
{
PropertyResourceBundle bundleUtf8 = new PropertyResourceBundle(isrUtf8); PropertyResourceBundle bundleUtf8 = new PropertyResourceBundle(isrUtf8);
PropertyResourceBundle bundle = new PropertyResourceBundle(fis8859_1); PropertyResourceBundle bundle = new PropertyResourceBundle(fis8859_1);
String[] arrayUtf8 = createKeyValueArray(bundleUtf8); String[] arrayUtf8 = createKeyValueArray(bundleUtf8);
String[] array = createKeyValueArray(bundle); String[] array = createKeyValueArray(bundle);
isrUtf8.close();
fisUtf8.close();
fis8859_1.close();
if (!Arrays.equals(arrayUtf8, array)) { 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."); 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.");
} }
......
...@@ -33,6 +33,7 @@ import java.io.FileInputStream; ...@@ -33,6 +33,7 @@ import java.io.FileInputStream;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Files;
import java.util.Scanner; import java.util.Scanner;
public class FailingConstructors { public class FailingConstructors {
...@@ -46,9 +47,7 @@ public class FailingConstructors { ...@@ -46,9 +47,7 @@ public class FailingConstructors {
/* create the file and write its contents */ /* create the file and write its contents */
File file = File.createTempFile(fileName, null); File file = File.createTempFile(fileName, null);
file.deleteOnExit(); file.deleteOnExit();
FileOutputStream fos = new FileOutputStream(file); Files.write(file.toPath(), FILE_CONTENTS.getBytes());
fos.write(FILE_CONTENTS.getBytes());
fos.close();
test(true, file); test(true, file);
file.delete(); file.delete();
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册