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

Reviewed-by: alanb, darcy, naoto
This commit is contained in:
Stuart Marks 2011-02-22 15:34:17 -08:00
parent 4ce8048909
commit dd0e38d73a
14 changed files with 150 additions and 175 deletions

View File

@ -576,12 +576,10 @@ public class Package implements java.lang.reflect.AnnotatedElement {
* 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;
}

View File

@ -233,7 +233,9 @@ public final class Currency implements Serializable {
"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])");

View File

@ -127,7 +127,9 @@ public class LocalGregorianCalendar extends BaseCalendar {
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;
}
});

View File

@ -571,9 +571,9 @@ class FileSystemPreferences extends AbstractPreferences {
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 @@ class FileSystemPreferences extends AbstractPreferences {
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);

View File

@ -12,40 +12,43 @@ import java.lang.Character.UnicodeScript;
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;
}
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);
}
ranges.add(start);
ranges.add(end);
}
}
sbfr.close();
// check all defined ranges
Integer[] ZEROSIZEARRAY = new Integer[0];
for (String name : scripts.keySet()) {

View File

@ -43,9 +43,9 @@ public class ShutdownHooks {
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 @@ public class ShutdownHooks {
// 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);
}

View File

@ -62,31 +62,33 @@ public class Setup {
* 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 */

View File

@ -118,23 +118,24 @@ public class Inject implements RuntimeConstants {
}
void dump(File outDir, String filename) throws IOException {
FileOutputStream fileOut = new FileOutputStream(new File(outDir, filename));
DataOutputStream dataOut = new DataOutputStream(fileOut);
try (FileOutputStream 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(); ) {
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) {

View File

@ -645,26 +645,17 @@ public class BigIntegerTest {
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 @@ public class BigIntegerTest {
System.err.println("Serialized failed for hex " +
b1.toString(16));
}
} finally {
fos.close();
}
f.delete();
}
@ -683,29 +672,17 @@ public class BigIntegerTest {
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) ||

View File

@ -111,57 +111,58 @@ public class ValidateISO4217 {
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]);

View File

@ -34,6 +34,7 @@ import java.io.FileOutputStream;
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 @@ public class FailingConstructors {
/* 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();

View File

@ -1187,14 +1187,12 @@ public class LocaleEnhanceTest extends LocaleTestFmwk {
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());
}

View File

@ -39,24 +39,19 @@ import java.util.PropertyResourceBundle;
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.");
}

View File

@ -33,6 +33,7 @@ import java.io.FileInputStream;
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 @@ public class FailingConstructors {
/* 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();