提交 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,40 +12,43 @@ import java.lang.Character.UnicodeScript; ...@@ -12,40 +12,43 @@ 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<>();
while ((line = sbfr.readLine()) != null) { try (BufferedReader sbfr = open(args)) {
if (line.length() <= 1 || line.charAt(0) == '#') { while ((line = sbfr.readLine()) != null) {
continue; if (line.length() <= 1 || line.charAt(0) == '#') {
} continue;
m.reset(line); }
if (m.matches()) { m.reset(line);
int start = Integer.parseInt(m.group(1), 16); if (m.matches()) {
int end = (m.group(2)==null)?start int start = Integer.parseInt(m.group(1), 16);
:Integer.parseInt(m.group(2), 16); int end = (m.group(2)==null)?start
String name = m.group(3).toLowerCase(Locale.ENGLISH); :Integer.parseInt(m.group(2), 16);
ArrayList<Integer> ranges = scripts.get(name); String name = m.group(3).toLowerCase(Locale.ENGLISH);
if (ranges == null) { ArrayList<Integer> ranges = scripts.get(name);
ranges = new ArrayList<Integer>(); if (ranges == null) {
scripts.put(name, ranges); ranges = new ArrayList<Integer>();
scripts.put(name, ranges);
}
ranges.add(start);
ranges.add(end);
} }
ranges.add(start);
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,31 +62,33 @@ public class Setup { ...@@ -62,31 +62,33 @@ 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 =
out.write(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++) { byte[] value = bootClassPath.getBytes("UTF-8");
int v = (int)value[i]; for (int i=0; i<value.length; i++) {
if (v < 0) v += 256; int v = (int)value[i];
byte[] escaped = ("%" + Integer.toHexString(v)).getBytes("UTF-8"); if (v < 0) v += 256;
out.write(escaped); 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" * 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,23 +118,24 @@ public class Inject implements RuntimeConstants { ...@@ -118,23 +118,24 @@ 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());
for (Iterator<Info> it = infoList.iterator(); it.hasNext(); ) { dataOut.writeInt(infoList.size());
Info info = it.next(); for (Iterator<Info> it = infoList.iterator(); it.hasNext(); ) {
if (!info.className.equals(currentClassName)) { Info info = it.next();
dataOut.writeInt(123456); // class name marker if (!info.className.equals(currentClassName)) {
currentClassName = info.className; dataOut.writeInt(123456); // class name marker
dataOut.writeUTF(currentClassName); 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) { 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,57 +111,58 @@ public class ValidateISO4217 { ...@@ -111,57 +111,58 @@ 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; {
SimpleDateFormat format = null; String line;
SimpleDateFormat format = null;
while ((line = in.readLine()) != null) {
if (line.length() == 0 || line.charAt(0) == '#') { while ((line = in.readLine()) != null) {
continue; if (line.length() == 0 || line.charAt(0) == '#') {
} continue;
}
StringTokenizer tokens = new StringTokenizer(line, "\t"); StringTokenizer tokens = new StringTokenizer(line, "\t");
String country = tokens.nextToken(); String country = tokens.nextToken();
if (country.length() != 2) { if (country.length() != 2) {
continue; continue;
} }
String currency; String currency;
String numeric; String numeric;
String minorUnit; String minorUnit;
int tokensCount = tokens.countTokens(); int tokensCount = tokens.countTokens();
if (tokensCount < 3) { if (tokensCount < 3) {
currency = ""; currency = "";
numeric = "0"; numeric = "0";
minorUnit = "0"; minorUnit = "0";
} else { } else {
currency = tokens.nextToken(); currency = tokens.nextToken();
numeric = tokens.nextToken(); numeric = tokens.nextToken();
minorUnit = tokens.nextToken(); minorUnit = tokens.nextToken();
testCurrencies.add(Currency.getInstance(currency)); testCurrencies.add(Currency.getInstance(currency));
// check for the cutover // check for the cutover
if (tokensCount > 3) { if (tokensCount > 3) {
if (format == null) { if (format == null) {
format = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss", Locale.US); format = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss", Locale.US);
format.setTimeZone(TimeZone.getTimeZone("GMT")); format.setTimeZone(TimeZone.getTimeZone("GMT"));
format.setLenient(false); format.setLenient(false);
} }
if (format.parse(tokens.nextToken()).getTime() < if (format.parse(tokens.nextToken()).getTime() <
System.currentTimeMillis()) { System.currentTimeMillis()) {
currency = tokens.nextToken(); currency = tokens.nextToken();
numeric = tokens.nextToken(); numeric = tokens.nextToken();
minorUnit = tokens.nextToken(); minorUnit = tokens.nextToken();
testCurrencies.add(Currency.getInstance(currency)); 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++) { 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", "."); try (FileInputStream fis8859_1 =
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.
先完成此消息的编辑!
想要评论请 注册