diff --git a/test/langtools/tools/javac/4241573/T4241573.java b/test/langtools/tools/javac/4241573/T4241573.java index 9a1c90fd679..9f4244bb834 100644 --- a/test/langtools/tools/javac/4241573/T4241573.java +++ b/test/langtools/tools/javac/4241573/T4241573.java @@ -131,16 +131,11 @@ public class T4241573 { /** Create a jar file containing one or more entries. */ File createJar(File jar, String... entries) throws IOException { - OutputStream out = new FileOutputStream(jar); - try { - JarOutputStream jos = new JarOutputStream(out); + try (JarOutputStream jos = new JarOutputStream(new FileOutputStream(jar))) { for (String e: entries) { jos.putNextEntry(new JarEntry(getPathForZipEntry(e))); jos.write(getBodyForEntry(e).getBytes()); } - jos.close(); - } finally { - out.close(); } return jar; } diff --git a/test/langtools/tools/javac/6400872/T6400872.java b/test/langtools/tools/javac/6400872/T6400872.java index c62f79db802..0772734d945 100644 --- a/test/langtools/tools/javac/6400872/T6400872.java +++ b/test/langtools/tools/javac/6400872/T6400872.java @@ -91,10 +91,9 @@ public class T6400872 { mainAttrs.put(Attributes.Name.MANIFEST_VERSION, "1.0"); mainAttrs.put(Attributes.Name.CLASS_PATH, join(classPath, " ")); } - OutputStream out = new BufferedOutputStream(new FileOutputStream(jar)); - JarOutputStream j = new JarOutputStream(out, m); - add(j, base, files); - j.close(); + try (JarOutputStream j = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(jar)), m)) { + add(j, base, files); + } } static void add(JarOutputStream j, File base, File... files) throws IOException { @@ -124,15 +123,16 @@ public class T6400872 { static byte[] read(File f) throws IOException { byte[] buf = new byte[(int) f.length()]; - BufferedInputStream in = new BufferedInputStream(new FileInputStream(f)); - int offset = 0; - while (offset < buf.length) { - int n = in.read(buf, offset, buf.length - offset); - if (n < 0) - throw new EOFException(); - offset += n; + try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(f))) { + int offset = 0; + while (offset < buf.length) { + int n = in.read(buf, offset, buf.length - offset); + if (n < 0) + throw new EOFException(); + offset += n; + } + return buf; } - return buf; } static Iterable iterable(T single) { diff --git a/test/langtools/tools/javac/6567415/T6567415.java b/test/langtools/tools/javac/6567415/T6567415.java index 223e33a5ca3..4c20150b9b4 100644 --- a/test/langtools/tools/javac/6567415/T6567415.java +++ b/test/langtools/tools/javac/6567415/T6567415.java @@ -64,13 +64,8 @@ public class T6567415 { com.sun.tools.javac.jvm.ClassReader.INITIAL_BUFFER_SIZE; static void createClassFile() throws IOException { - FileOutputStream fos = null; - try { - fos = new FileOutputStream(TEST_JAVA); - PrintStream ps = new PrintStream(fos); + try (PrintStream ps = new PrintStream(new FileOutputStream(TEST_JAVA))) { ps.println("public class " + TEST_FILE_NAME + " {}"); - } finally { - fos.close(); } String cmds[] = {TEST_JAVA}; com.sun.tools.javac.Main.compile(cmds); @@ -85,43 +80,23 @@ public class T6567415 { File tfile = new File(f.getAbsolutePath() + ".tmp"); f.renameTo(tfile); - RandomAccessFile raf = null; - FileChannel wfc = null; - - FileInputStream fis = null; - FileChannel rfc = null; - - try { - raf = new RandomAccessFile(f, "rw"); - wfc = raf.getChannel(); - - fis = new FileInputStream(tfile); - rfc = fis.getChannel(); - + try ( + FileChannel wfc = new RandomAccessFile(f, "rw").getChannel(); + FileChannel rfc = new FileInputStream(tfile).getChannel()) { ByteBuffer bb = MappedByteBuffer.allocate(BAD_FILE_LENGTH); rfc.read(bb); bb.rewind(); wfc.write(bb); wfc.truncate(BAD_FILE_LENGTH); - } finally { - wfc.close(); - raf.close(); - rfc.close(); - fis.close(); } System.out.println("file length = " + f.length()); } static void createJavaFile() throws IOException { - FileOutputStream fos = null; - try { - fos = new FileOutputStream(TEST2_JAVA); - PrintStream ps = new PrintStream(fos); + try (PrintStream ps = new PrintStream(new FileOutputStream(TEST2_JAVA))) { ps.println("public class " + TEST2_FILE_NAME + " {" + TEST_FILE_NAME + " b = new " + TEST_FILE_NAME + " ();}"); - } finally { - fos.close(); } } diff --git a/test/langtools/tools/javac/ConditionalExpressionResolvePending.java b/test/langtools/tools/javac/ConditionalExpressionResolvePending.java index ac2a1de44d9..11e62a25308 100644 --- a/test/langtools/tools/javac/ConditionalExpressionResolvePending.java +++ b/test/langtools/tools/javac/ConditionalExpressionResolvePending.java @@ -42,6 +42,7 @@ import combo.ComboInstance; import combo.ComboParameter; import combo.ComboTask; import combo.ComboTestHelper; +import java.io.InputStream; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Iterator; @@ -110,7 +111,10 @@ public class ConditionalExpressionResolvePending extends ComboInstance findClass(String name) throws ClassNotFoundException { if ("Test".equals(name)) { diff --git a/test/langtools/tools/javac/NoStringToLower.java b/test/langtools/tools/javac/NoStringToLower.java index bd1ff8bf346..757881f9332 100644 --- a/test/langtools/tools/javac/NoStringToLower.java +++ b/test/langtools/tools/javac/NoStringToLower.java @@ -102,8 +102,7 @@ public class NoStringToLower { * Verify there are no references to String.toLowerCase() in a class file. */ void scan(JavaFileObject fo) throws IOException { - InputStream in = fo.openInputStream(); - try { + try (InputStream in = fo.openInputStream()) { ClassFile cf = ClassFile.read(in); for (ConstantPool.CPInfo cpinfo: cf.constant_pool.entries()) { if (cpinfo.getTag() == ConstantPool.CONSTANT_Methodref) { @@ -119,8 +118,6 @@ public class NoStringToLower { } } } catch (ConstantPoolException ignore) { - } finally { - in.close(); } } diff --git a/test/langtools/tools/javac/Paths/6638501/JarFromManifestFailure.java b/test/langtools/tools/javac/Paths/6638501/JarFromManifestFailure.java index e5650e6cccd..698ebb6e80f 100644 --- a/test/langtools/tools/javac/Paths/6638501/JarFromManifestFailure.java +++ b/test/langtools/tools/javac/Paths/6638501/JarFromManifestFailure.java @@ -106,10 +106,9 @@ public class JarFromManifestFailure { mainAttrs.put(Attributes.Name.MANIFEST_VERSION, "1.0"); mainAttrs.put(Attributes.Name.CLASS_PATH, join(classPath, " ")); } - OutputStream out = new BufferedOutputStream(new FileOutputStream(jar)); - JarOutputStream j = new JarOutputStream(out, m); - add(j, base, files); - j.close(); + try (JarOutputStream j = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(jar)), m)) { + add(j, base, files); + } } static void add(JarOutputStream j, File base, File... files) throws IOException { @@ -144,15 +143,16 @@ public class JarFromManifestFailure { static byte[] read(File f) throws IOException { byte[] buf = new byte[(int) f.length()]; - BufferedInputStream in = new BufferedInputStream(new FileInputStream(f)); - int offset = 0; - while (offset < buf.length) { - int n = in.read(buf, offset, buf.length - offset); - if (n < 0) - throw new EOFException(); - offset += n; + try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(f))) { + int offset = 0; + while (offset < buf.length) { + int n = in.read(buf, offset, buf.length - offset); + if (n < 0) + throw new EOFException(); + offset += n; + } + return buf; } - return buf; } static Iterable iterable(T single) { diff --git a/test/langtools/tools/javac/Paths/TestCompileJARInClassPath.java b/test/langtools/tools/javac/Paths/TestCompileJARInClassPath.java index e377d0dd4cd..a653143d2b8 100644 --- a/test/langtools/tools/javac/Paths/TestCompileJARInClassPath.java +++ b/test/langtools/tools/javac/Paths/TestCompileJARInClassPath.java @@ -63,9 +63,9 @@ public class TestCompileJARInClassPath { } void writeFile(String f, String contents) throws IOException { - PrintStream s = new PrintStream(new FileOutputStream(f)); - s.println(contents); - s.close(); + try (PrintStream s = new PrintStream(new FileOutputStream(f))) { + s.println(contents); + } } void rm(String filename) throws Exception { diff --git a/test/langtools/tools/javac/T6403466.java b/test/langtools/tools/javac/T6403466.java index 6945d89e200..1251c64ba9f 100644 --- a/test/langtools/tools/javac/T6403466.java +++ b/test/langtools/tools/javac/T6403466.java @@ -84,10 +84,8 @@ public class T6403466 extends AbstractProcessor { System.err.println("anno: " + anno); System.err.println("elts: " + elts); for (TypeElement te: ElementFilter.typesIn(elts)) { - try { - Writer out = filer.createSourceFile(te.getSimpleName() + "Wrapper").openWriter(); + try (Writer out = filer.createSourceFile(te.getSimpleName() + "Wrapper").openWriter()) { out.write("class " + te.getSimpleName() + "Wrapper { }"); - out.close(); } catch (IOException ex) { ex.printStackTrace(); } diff --git a/test/langtools/tools/javac/T7159016.java b/test/langtools/tools/javac/T7159016.java index 12648cd777d..be8d7ce082f 100644 --- a/test/langtools/tools/javac/T7159016.java +++ b/test/langtools/tools/javac/T7159016.java @@ -78,13 +78,8 @@ public class T7159016 { return false; } messager.printNote("writing Generated.java"); - try { - Writer w = processingEnv.getFiler().createSourceFile("p.Generated").openWriter(); - try { - w.write("package p; public class Generated { public static void m() { } }"); - } finally { - w.close(); - } + try (Writer w = processingEnv.getFiler().createSourceFile("p.Generated").openWriter()) { + w.write("package p; public class Generated { public static void m() { } }"); } catch (IOException x) { messager.printError(x.toString()); } diff --git a/test/langtools/tools/javac/T8003967/DetectMutableStaticFields.java b/test/langtools/tools/javac/T8003967/DetectMutableStaticFields.java index 9d2f83bb372..f25c0099fe7 100644 --- a/test/langtools/tools/javac/T8003967/DetectMutableStaticFields.java +++ b/test/langtools/tools/javac/T8003967/DetectMutableStaticFields.java @@ -32,6 +32,7 @@ import java.io.File; import java.io.IOException; +import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; @@ -178,7 +179,11 @@ public class DetectMutableStaticFields { int index = className.lastIndexOf('.'); String pckName = index == -1 ? "" : className.substring(0, index); if (shouldAnalyzePackage(pckName)) { - analyzeClassFile(ClassFile.read(file.openInputStream())); + ClassFile classFile; + try (InputStream input = file.openInputStream()) { + classFile = ClassFile.read(input); + } + analyzeClassFile(classFile); } } } diff --git a/test/langtools/tools/javac/T8071847/T8071847.java b/test/langtools/tools/javac/T8071847/T8071847.java index 9c030ded5af..d07d53cb7c3 100644 --- a/test/langtools/tools/javac/T8071847/T8071847.java +++ b/test/langtools/tools/javac/T8071847/T8071847.java @@ -83,9 +83,9 @@ public class T8071847 { File writeHexFile(String classFileName, String hexString) throws IOException { File f = new File(classFileName); - FileOutputStream output = new FileOutputStream(f); - output.write(hexToByte(hexString)); - output.close(); + try (FileOutputStream output = new FileOutputStream(f)) { + output.write(hexToByte(hexString)); + } return f; } diff --git a/test/langtools/tools/javac/T8152616.java b/test/langtools/tools/javac/T8152616.java index e2c6d38eaf6..a7b64791b03 100644 --- a/test/langtools/tools/javac/T8152616.java +++ b/test/langtools/tools/javac/T8152616.java @@ -60,15 +60,17 @@ public class T8152616 { JavacTool javac = JavacTool.create(); StandardJavaFileManager jfm = javac.getStandardFileManager(null,null,null); File file = File.createTempFile("test", ".java"); - OutputStream outputStream = new FileOutputStream(file); - outputStream.write("enum Foo {AA(10), BB, CC { void m() {} }; void m() {};}".getBytes()); + try (OutputStream outputStream = new FileOutputStream(file)) { + outputStream.write("enum Foo {AA(10), BB, CC { void m() {} }; void m() {};}".getBytes()); + } JavacTask task = javac.getTask(null, jfm, null, null, null, jfm.getJavaFileObjects(file.getAbsolutePath())); Iterable trees = task.parse(); CompilationUnitTree thisTree = trees.iterator().next(); file.delete(); - outputStream = new FileOutputStream(file); - outputStream.write((obj.PrettyPrint((JCTree)thisTree)).getBytes()); + try (OutputStream outputStream = new FileOutputStream(file)) { + outputStream.write((obj.PrettyPrint((JCTree)thisTree)).getBytes()); + } task = javac.getTask(null, jfm, null, null, null, jfm.getJavaFileObjects(file.getAbsolutePath())); if(task.parse().toString().contains("ERROR")){ diff --git a/test/langtools/tools/javac/api/T6483788.java b/test/langtools/tools/javac/api/T6483788.java index 3bf6908a3b8..044d42df428 100644 --- a/test/langtools/tools/javac/api/T6483788.java +++ b/test/langtools/tools/javac/api/T6483788.java @@ -58,14 +58,9 @@ public class T6483788 { File createJar() throws IOException { byte[] dummy_data = new byte[10]; File f = new File("a b.jar"); - OutputStream out = new FileOutputStream(f); - try { - JarOutputStream jar = new JarOutputStream(out); + try (JarOutputStream jar = new JarOutputStream(new FileOutputStream(f))) { jar.putNextEntry(new ZipEntry("dummy.class")); jar.write(dummy_data); - jar.close(); - } finally { - out.close(); } return f; } diff --git a/test/langtools/tools/javac/api/T6877206.java b/test/langtools/tools/javac/api/T6877206.java index 77fd394b8a6..60d41a214b2 100644 --- a/test/langtools/tools/javac/api/T6877206.java +++ b/test/langtools/tools/javac/api/T6877206.java @@ -114,8 +114,14 @@ public class T6877206 { } try { - byte[] uriData = read(urlconn.getInputStream()); - byte[] foData = read(fo.openInputStream()); + byte[] uriData; + byte[] foData; + try (InputStream input = urlconn.getInputStream()) { + uriData = read(input); + } + try (InputStream input = fo.openInputStream()) { + foData = read(input); + } if (!Arrays.equals(uriData, foData)) { if (uriData.length != foData.length) throw new Exception("data size differs: uri data " @@ -174,16 +180,11 @@ public class T6877206 { File createJar(String name, String... entries) throws IOException { File jar = new File(name); - OutputStream out = new FileOutputStream(jar); - try { - JarOutputStream jos = new JarOutputStream(out); + try (JarOutputStream jos = new JarOutputStream(new FileOutputStream(jar))) { for (String e: entries) { jos.putNextEntry(new ZipEntry(e)); jos.write(e.getBytes()); } - jos.close(); - } finally { - out.close(); } return jar; } diff --git a/test/langtools/tools/javac/api/guide/Test.java b/test/langtools/tools/javac/api/guide/Test.java index 579305477f4..64b2a304016 100644 --- a/test/langtools/tools/javac/api/guide/Test.java +++ b/test/langtools/tools/javac/api/guide/Test.java @@ -36,6 +36,7 @@ import javax.tools.*; import java.io.File; +import java.io.Reader; import java.util.Collections; public class Test extends ToolTester { @@ -45,10 +46,10 @@ public class Test extends ToolTester { class DiagnosticTester implements DiagnosticListener { public void report(Diagnostic diagnostic) { if (diagnostic.getKind() == Diagnostic.Kind.NOTE) { - try { - // 6427274: FileObject.openReader throws exception - // 6347778: getSource() returns null for notes - diagnostic.getSource().openReader(true).getClass(); + // 6427274: FileObject.openReader throws exception + // 6347778: getSource() returns null for notes + try (Reader reader = diagnostic.getSource().openReader(true)) { + reader.getClass(); } catch (Exception ex) { throw new AssertionError(ex); } @@ -66,9 +67,11 @@ public class Test extends ToolTester { if (!success) throw new AssertionError("Did not see a NOTE"); // 6427274: openReader throws exception - fm.getFileForInput(StandardLocation.PLATFORM_CLASS_PATH, + try (Reader reader = fm.getFileForInput(StandardLocation.PLATFORM_CLASS_PATH, "java.lang", - "Object.class").openReader(true).getClass(); + "Object.class").openReader(true)) { + reader.getClass(); + } DiagnosticCollector diags = new DiagnosticCollector(); task = tool.getTask(null, fm, diags, Collections.singleton("-Xlint:all"), null, compilationUnits); diff --git a/test/langtools/tools/javac/classfiles/attributes/LineNumberTable/LineNumberTestBase.java b/test/langtools/tools/javac/classfiles/attributes/LineNumberTable/LineNumberTestBase.java index d0023a53dbb..8914617f2c9 100644 --- a/test/langtools/tools/javac/classfiles/attributes/LineNumberTable/LineNumberTestBase.java +++ b/test/langtools/tools/javac/classfiles/attributes/LineNumberTable/LineNumberTestBase.java @@ -23,6 +23,7 @@ import com.sun.tools.classfile.*; +import java.io.InputStream; import java.nio.file.Paths; import java.util.HashSet; import java.util.List; @@ -66,7 +67,10 @@ public class LineNumberTestBase extends TestBase { writeToFileIfEnabled(Paths.get(testCase.getName() + ".java"), testCase.src); Set coveredLines = new HashSet<>(); for (JavaFileObject file : compile(testCase.extraCompilerOptions, testCase.src).getClasses().values()) { - ClassFile classFile = ClassFile.read(file.openInputStream()); + ClassFile classFile; + try (InputStream input = file.openInputStream()) { + classFile = ClassFile.read(input); + } for (Method m : classFile.methods) { Code_attribute code_attribute = (Code_attribute) m.attributes.get(Code); diff --git a/test/langtools/tools/javac/classfiles/attributes/SourceFile/SourceFileTestBase.java b/test/langtools/tools/javac/classfiles/attributes/SourceFile/SourceFileTestBase.java index b3a13bd5dfd..f7f27e0af4e 100644 --- a/test/langtools/tools/javac/classfiles/attributes/SourceFile/SourceFileTestBase.java +++ b/test/langtools/tools/javac/classfiles/attributes/SourceFile/SourceFileTestBase.java @@ -25,6 +25,7 @@ import com.sun.tools.classfile.Attribute; import com.sun.tools.classfile.ClassFile; import com.sun.tools.classfile.SourceFile_attribute; +import java.io.InputStream; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; @@ -84,7 +85,11 @@ public class SourceFileTestBase extends TestBase { Map classes = compile(sourceCode).getClasses(); String fileName = ToolBox.getJavaFileNameFromSource(sourceCode); for (String className : classesToTest) { - assertAttributePresent(ClassFile.read(classes.get(className).openInputStream()), fileName); + ClassFile classFile; + try (InputStream input = classes.get(className).openInputStream()) { + classFile = ClassFile.read(input); + } + assertAttributePresent(classFile, fileName); } } diff --git a/test/langtools/tools/javac/diags/CheckExamples.java b/test/langtools/tools/javac/diags/CheckExamples.java index f27aca40ec5..dd763f3d3da 100644 --- a/test/langtools/tools/javac/diags/CheckExamples.java +++ b/test/langtools/tools/javac/diags/CheckExamples.java @@ -199,11 +199,8 @@ public class CheckExamples { */ String read(File f) throws IOException { byte[] bytes = new byte[(int) f.length()]; - DataInputStream in = new DataInputStream(new FileInputStream(f)); - try { + try (DataInputStream in = new DataInputStream(new FileInputStream(f))) { in.readFully(bytes); - } finally { - in.close(); } return new String(bytes); } diff --git a/test/langtools/tools/javac/diags/CheckResourceKeys.java b/test/langtools/tools/javac/diags/CheckResourceKeys.java index 4b2d198113b..b404d568fc3 100644 --- a/test/langtools/tools/javac/diags/CheckResourceKeys.java +++ b/test/langtools/tools/javac/diags/CheckResourceKeys.java @@ -489,8 +489,7 @@ public class CheckResourceKeys { * Only strings that look like they might be a resource key are returned. */ void scan(JavaFileObject fo, Set results) throws IOException { - InputStream in = fo.openInputStream(); - try { + try (InputStream in = fo.openInputStream()) { ClassFile cf = ClassFile.read(in); for (ConstantPool.CPInfo cpinfo: cf.constant_pool.entries()) { if (cpinfo.getTag() == ConstantPool.CONSTANT_Utf8) { @@ -500,8 +499,6 @@ public class CheckResourceKeys { } } } catch (ConstantPoolException ignore) { - } finally { - in.close(); } } diff --git a/test/langtools/tools/javac/diags/Example.java b/test/langtools/tools/javac/diags/Example.java index 8accf99788a..dbba0318136 100644 --- a/test/langtools/tools/javac/diags/Example.java +++ b/test/langtools/tools/javac/diags/Example.java @@ -429,11 +429,8 @@ class Example implements Comparable { */ private String read(File f) throws IOException { byte[] bytes = new byte[(int) f.length()]; - DataInputStream in = new DataInputStream(new FileInputStream(f)); - try { + try (DataInputStream in = new DataInputStream(new FileInputStream(f))) { in.readFully(bytes); - } finally { - in.close(); } return new String(bytes); } diff --git a/test/langtools/tools/javac/diags/MessageInfo.java b/test/langtools/tools/javac/diags/MessageInfo.java index 86b0304c64d..8bfc409cdb8 100644 --- a/test/langtools/tools/javac/diags/MessageInfo.java +++ b/test/langtools/tools/javac/diags/MessageInfo.java @@ -380,11 +380,8 @@ public class MessageInfo { */ String read(File f) throws IOException { byte[] bytes = new byte[(int) f.length()]; - DataInputStream in = new DataInputStream(new FileInputStream(f)); - try { + try (DataInputStream in = new DataInputStream(new FileInputStream(f))) { in.readFully(bytes); - } finally { - in.close(); } return new String(bytes); } diff --git a/test/langtools/tools/javac/diags/RunExamples.java b/test/langtools/tools/javac/diags/RunExamples.java index 3993afa30a6..7e956aefb36 100644 --- a/test/langtools/tools/javac/diags/RunExamples.java +++ b/test/langtools/tools/javac/diags/RunExamples.java @@ -261,11 +261,8 @@ public class RunExamples { protected String read(File f) throws IOException { byte[] bytes = new byte[(int) f.length()]; - DataInputStream in = new DataInputStream(new FileInputStream(f)); - try { + try (DataInputStream in = new DataInputStream(new FileInputStream(f))) { in.readFully(bytes); - } finally { - in.close(); } return new String(bytes); } diff --git a/test/langtools/tools/javac/diags/examples/ProcFileCreateLastRound/processors/AnnoProc.java b/test/langtools/tools/javac/diags/examples/ProcFileCreateLastRound/processors/AnnoProc.java index a9ee3448714..eb6086e8a1f 100644 --- a/test/langtools/tools/javac/diags/examples/ProcFileCreateLastRound/processors/AnnoProc.java +++ b/test/langtools/tools/javac/diags/examples/ProcFileCreateLastRound/processors/AnnoProc.java @@ -36,9 +36,9 @@ public class AnnoProc extends AbstractProcessor { Messager messager = processingEnv.getMessager(); try { JavaFileObject fo = filer.createSourceFile("Gen"); - Writer out = fo.openWriter(); - out.write("class Gen { }"); - out.close(); + try (Writer out = fo.openWriter()) { + out.write("class Gen { }"); + } } catch (IOException e) { messager.printError(e.toString()); } diff --git a/test/langtools/tools/javac/diags/examples/ProcFileReopening/processors/AnnoProc.java b/test/langtools/tools/javac/diags/examples/ProcFileReopening/processors/AnnoProc.java index 46523e5f1a0..7c8ac800e0a 100644 --- a/test/langtools/tools/javac/diags/examples/ProcFileReopening/processors/AnnoProc.java +++ b/test/langtools/tools/javac/diags/examples/ProcFileReopening/processors/AnnoProc.java @@ -37,9 +37,9 @@ public class AnnoProc extends AbstractProcessor { try { FileObject fo1 = filer.createResource( StandardLocation.CLASS_OUTPUT, "", "HelloWorld.txt"); - Writer out = fo1.openWriter(); - out.write("Hello World!"); - out.close(); + try (Writer out = fo1.openWriter()) { + out.write("Hello World!"); + } FileObject fo2 = filer.createResource( StandardLocation.CLASS_OUTPUT, "", "HelloWorld.txt"); } catch (IOException e) { diff --git a/test/langtools/tools/javac/diags/examples/ProcIllegalFileName/processors/AnnoProc.java b/test/langtools/tools/javac/diags/examples/ProcIllegalFileName/processors/AnnoProc.java index 8cf91cf3ddb..d0bc5afde8b 100644 --- a/test/langtools/tools/javac/diags/examples/ProcIllegalFileName/processors/AnnoProc.java +++ b/test/langtools/tools/javac/diags/examples/ProcIllegalFileName/processors/AnnoProc.java @@ -37,9 +37,9 @@ public class AnnoProc extends AbstractProcessor { try { FileObject fo1 = filer.createResource( StandardLocation.CLASS_OUTPUT, "p+q", "Hello-World.txt"); - Writer out = fo1.openWriter(); - out.write("Hello World!"); - out.close(); + try (Writer out = fo1.openWriter()) { + out.write("Hello World!"); + } } catch (IOException e) { messager.printError(e.toString()); } diff --git a/test/langtools/tools/javac/diags/examples/ProcTypeRecreate/processors/AnnoProc.java b/test/langtools/tools/javac/diags/examples/ProcTypeRecreate/processors/AnnoProc.java index 8a595ec193e..1126c52acbe 100644 --- a/test/langtools/tools/javac/diags/examples/ProcTypeRecreate/processors/AnnoProc.java +++ b/test/langtools/tools/javac/diags/examples/ProcTypeRecreate/processors/AnnoProc.java @@ -37,9 +37,9 @@ public class AnnoProc extends AbstractProcessor { Messager messager = processingEnv.getMessager(); try { JavaFileObject fo = filer.createSourceFile("Gen"); - Writer out = fo.openWriter(); - out.write("class Gen { }"); - out.close(); + try (Writer out = fo.openWriter()) { + out.write("class Gen { }"); + } } catch (IOException e) { messager.printError(e.toString()); } diff --git a/test/langtools/tools/javac/diags/examples/ProcUseImplicit/processors/AnnoProc.java b/test/langtools/tools/javac/diags/examples/ProcUseImplicit/processors/AnnoProc.java index 5d8996e652e..2fa4526aa57 100644 --- a/test/langtools/tools/javac/diags/examples/ProcUseImplicit/processors/AnnoProc.java +++ b/test/langtools/tools/javac/diags/examples/ProcUseImplicit/processors/AnnoProc.java @@ -36,9 +36,9 @@ public class AnnoProc extends AbstractProcessor { Messager messager = processingEnv.getMessager(); try { JavaFileObject fo = filer.createSourceFile("Gen"); - Writer out = fo.openWriter(); - out.write("class Gen { }"); - out.close(); + try (Writer out = fo.openWriter()) { + out.write("class Gen { }"); + } } catch (IOException e) { messager.printError(e.toString()); } diff --git a/test/langtools/tools/javac/diags/examples/ProcUseProcOrImplicit/processors/AnnoProc.java b/test/langtools/tools/javac/diags/examples/ProcUseProcOrImplicit/processors/AnnoProc.java index 5d8996e652e..2fa4526aa57 100644 --- a/test/langtools/tools/javac/diags/examples/ProcUseProcOrImplicit/processors/AnnoProc.java +++ b/test/langtools/tools/javac/diags/examples/ProcUseProcOrImplicit/processors/AnnoProc.java @@ -36,9 +36,9 @@ public class AnnoProc extends AbstractProcessor { Messager messager = processingEnv.getMessager(); try { JavaFileObject fo = filer.createSourceFile("Gen"); - Writer out = fo.openWriter(); - out.write("class Gen { }"); - out.close(); + try (Writer out = fo.openWriter()) { + out.write("class Gen { }"); + } } catch (IOException e) { messager.printError(e.toString()); } diff --git a/test/langtools/tools/javac/doctree/dcapi/DocCommentTreeApiTester.java b/test/langtools/tools/javac/doctree/dcapi/DocCommentTreeApiTester.java index d03cbc3d45b..c2196e31294 100644 --- a/test/langtools/tools/javac/doctree/dcapi/DocCommentTreeApiTester.java +++ b/test/langtools/tools/javac/doctree/dcapi/DocCommentTreeApiTester.java @@ -203,7 +203,7 @@ public class DocCommentTreeApiTester { t.getElements().getPackageOf(klass).getQualifiedName().toString(), fileName + ".out"); - String expected = getExpected(htmlFo.openReader(true)); + String expected = getExpectedAndClose(htmlFo.openReader(true)); astcheck(fileName, expected, found); } } @@ -239,7 +239,7 @@ public class DocCommentTreeApiTester { throw new Exception("invalid input: " + jfo); break; default: - expected = getExpected(jfo.openReader(true)); + expected = getExpectedAndClose(jfo.openReader(true)); } } @@ -297,7 +297,7 @@ public class DocCommentTreeApiTester { String found = sw.toString(); Iterable oos = fm.getJavaFileObjectsFromFiles(otherFiles); JavaFileObject otherFo = oos.iterator().next(); - String expected = getExpected(otherFo.openReader(true)); + String expected = getExpectedAndClose(otherFo.openReader(true)); astcheck(pkgFileName, expected, found); } @@ -323,13 +323,14 @@ public class DocCommentTreeApiTester { } } - String getExpected(Reader inrdr) throws IOException { - BufferedReader rdr = new BufferedReader(inrdr); + String getExpectedAndClose(Reader inrdr) throws IOException { List lines = new ArrayList<>(); - String line = rdr.readLine(); - while (line != null) { - lines.add(line); - line = rdr.readLine(); + try (BufferedReader rdr = new BufferedReader(inrdr)) { + String line = rdr.readLine(); + while (line != null) { + lines.add(line); + line = rdr.readLine(); + } } return getExpected(lines); } diff --git a/test/langtools/tools/javac/file/T7068437.java b/test/langtools/tools/javac/file/T7068437.java index 2b857df1b9a..d279b350536 100644 --- a/test/langtools/tools/javac/file/T7068437.java +++ b/test/langtools/tools/javac/file/T7068437.java @@ -118,10 +118,8 @@ public class T7068437 { messager.printError("expected file but file not found"); } - try { - Writer w = filer.createSourceFile("p.C").openWriter(); + try (Writer w = filer.createSourceFile("p.C").openWriter()) { w.write("/* hello! */ package p; class C {}"); - w.close(); messager.printNote("wrote new content"); } catch (IOException x) { messager.printError("while writing: " + x); diff --git a/test/langtools/tools/javac/file/T7068451.java b/test/langtools/tools/javac/file/T7068451.java index 54de43b8219..5aae30192e1 100644 --- a/test/langtools/tools/javac/file/T7068451.java +++ b/test/langtools/tools/javac/file/T7068451.java @@ -151,11 +151,9 @@ public class T7068451 { messager.printError("while reading: " + x); } - try { - String body = "package p; public class C { public static void " + m + "() {} }"; - Writer w = filer.createSourceFile("p.C").openWriter(); + String body = "package p; public class C { public static void " + m + "() {} }"; + try (Writer w = filer.createSourceFile("p.C").openWriter()) { w.write(body); - w.close(); messager.printNote("C.java: wrote new content: " + body); } catch (IOException x) { messager.printError("while writing: " + x); diff --git a/test/langtools/tools/javac/file/zip/T6836682.java b/test/langtools/tools/javac/file/zip/T6836682.java index ab8e7440a6b..582c7870623 100644 --- a/test/langtools/tools/javac/file/zip/T6836682.java +++ b/test/langtools/tools/javac/file/zip/T6836682.java @@ -79,19 +79,12 @@ public class T6836682 { static long computeCRC(File inFile) throws IOException { byte[] buffer = new byte[8192]; CRC32 crc = new CRC32(); - FileInputStream fis = null; - BufferedInputStream bis = null; - try { - fis = new FileInputStream(inFile); - bis = new BufferedInputStream(fis); + try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(inFile))) { int n = bis.read(buffer); while (n > 0) { crc.update(buffer, 0, n); n = bis.read(buffer); } - } finally { - Utils.close(bis); - Utils.close(fis); } return crc.getValue(); } @@ -109,14 +102,11 @@ public class T6836682 { long minlength) throws IOException { Utils.createClassFile(javaFile, null, true); File classFile = new File(Utils.getClassFileName(javaFile)); - ZipOutputStream zos = null; - BufferedOutputStream bos = null; - FileInputStream fis = null; - try { - zos = new ZipOutputStream(new FileOutputStream(jarFile)); + try ( + ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(jarFile)); + BufferedOutputStream bos = new BufferedOutputStream(zos)) { zos.setLevel(ZipOutputStream.STORED); zos.setMethod(0); - bos = new BufferedOutputStream(zos); ZipEntry ze = new ZipEntry("large.data"); ze.setCompressedSize(getCount(minlength) * BUFFER_LEN); @@ -132,14 +122,11 @@ public class T6836682 { ze.setCrc(computeCRC(classFile)); ze.setMethod(ZipEntry.STORED); zos.putNextEntry(ze); - fis = new FileInputStream(classFile); - Utils.copyStream(fis, bos); + try (FileInputStream fis = new FileInputStream(classFile)) { + Utils.copyStream(fis, bos); + } bos.flush(); zos.closeEntry(); - } finally { - Utils.close(bos); - Utils.close(zos); - Utils.close(fis); } // deleted to prevent accidental linkage new File(Utils.getClassFileName(javaFile)).delete(); @@ -148,12 +135,9 @@ public class T6836682 { static void createLargeJar(File jarFile, File javaFile) throws IOException { File classFile = new File(Utils.getClassFileName(javaFile)); Utils.createClassFile(javaFile, null, true); - ZipOutputStream zos = null; - FileInputStream fis = null; final int MAX = Short.MAX_VALUE * 2 + 10; ZipEntry ze = null; - try { - zos = new ZipOutputStream(new FileOutputStream(jarFile)); + try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(jarFile))) { zos.setLevel(ZipOutputStream.STORED); zos.setMethod(ZipOutputStream.STORED); for (int i = 0; i < MAX ; i++) { @@ -170,14 +154,13 @@ public class T6836682 { ze.setSize(classFile.length()); ze.setCrc(computeCRC(classFile)); zos.putNextEntry(ze); - fis = new FileInputStream(classFile); - Utils.copyStream(fis, zos); + try (FileInputStream fis = new FileInputStream(classFile)) { + Utils.copyStream(fis, zos); + } } finally { - Utils.close(zos); - Utils.close(fis); - // deleted to prevent accidental linkage - new File(Utils.getClassFileName(javaFile)).delete(); - } + // deleted to prevent accidental linkage + new File(Utils.getClassFileName(javaFile)).delete(); + } } // a jar with entries exceeding 64k + a class file for the existential test diff --git a/test/langtools/tools/javac/file/zip/Utils.java b/test/langtools/tools/javac/file/zip/Utils.java index 35e7c6d0c07..da080151593 100644 --- a/test/langtools/tools/javac/file/zip/Utils.java +++ b/test/langtools/tools/javac/file/zip/Utils.java @@ -66,18 +66,13 @@ public class Utils { } public static void createJavaFile(File outFile, File superClass) throws IOException { - PrintStream ps = null; String srcStr = "public class " + getSimpleName(outFile) + " "; if (superClass != null) { srcStr = srcStr.concat("extends " + getSimpleName(superClass) + " "); } srcStr = srcStr.concat("{}"); - try { - FileOutputStream fos = new FileOutputStream(outFile); - ps = new PrintStream(fos); + try (PrintStream ps = new PrintStream(new FileOutputStream(outFile))) { ps.println(srcStr); - } finally { - close(ps); } } @@ -116,22 +111,12 @@ public class Utils { } public static void cat(File output, File... files) throws IOException { - BufferedInputStream bis = null; - BufferedOutputStream bos = null; - FileOutputStream fos = null; - try { - fos = new FileOutputStream(output); - bos = new BufferedOutputStream(fos); - for (File x : files) { - FileInputStream fis = new FileInputStream(x); - bis = new BufferedInputStream(fis); - copyStream(bis, bos); - Utils.close(bis); + try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(output))) { + for (File file : files) { + try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) { + copyStream(bis, bos); + } } - } finally { - Utils.close(bis); - Utils.close(bos); - Utils.close(fos); } } } diff --git a/test/langtools/tools/javac/lambda/deduplication/DeduplicationTest.java b/test/langtools/tools/javac/lambda/deduplication/DeduplicationTest.java index e80724c35fa..a98348adb1e 100644 --- a/test/langtools/tools/javac/lambda/deduplication/DeduplicationTest.java +++ b/test/langtools/tools/javac/lambda/deduplication/DeduplicationTest.java @@ -62,6 +62,7 @@ import com.sun.tools.javac.tree.JCTree.Tag; import com.sun.tools.javac.tree.TreeScanner; import com.sun.tools.javac.util.Context; import com.sun.tools.javac.util.JCDiagnostic; +import java.io.InputStream; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; @@ -135,7 +136,10 @@ public class DeduplicationTest { // lambdas. Set bootstrapMethodNames = new TreeSet<>(); for (JavaFileObject output : generated) { - ClassFile cf = ClassFile.read(output.openInputStream()); + ClassFile cf; + try (InputStream input = output.openInputStream()) { + cf = ClassFile.read(input); + } if (cf.getName().equals("com/sun/tools/javac/comp/Deduplication$R")) { continue; } diff --git a/test/langtools/tools/javac/lambdaShapes/org/openjdk/tests/separate/DirectedClassLoader.java b/test/langtools/tools/javac/lambdaShapes/org/openjdk/tests/separate/DirectedClassLoader.java index 945009b663c..c33dee22455 100644 --- a/test/langtools/tools/javac/lambdaShapes/org/openjdk/tests/separate/DirectedClassLoader.java +++ b/test/langtools/tools/javac/lambdaShapes/org/openjdk/tests/separate/DirectedClassLoader.java @@ -75,24 +75,18 @@ class DirectedClassLoader extends ClassLoader { } private Class defineFrom(String name, File file) { - FileInputStream fis = null; - try { - try { - fis = new FileInputStream(file); - byte[] bytes = new byte[fis.available()]; - int read = fis.read(bytes); - if (read != bytes.length) { - return null; - } - if (preprocessors != null) { - for (ClassFilePreprocessor cfp : preprocessors) { - bytes = cfp.preprocess(name, bytes); - } - } - return defineClass(name, bytes, 0, bytes.length); - } finally { - fis.close(); + try (FileInputStream fis = new FileInputStream(file)) { + byte[] bytes = new byte[fis.available()]; + int read = fis.read(bytes); + if (read != bytes.length) { + return null; } + if (preprocessors != null) { + for (ClassFilePreprocessor cfp : preprocessors) { + bytes = cfp.preprocess(name, bytes); + } + } + return defineClass(name, bytes, 0, bytes.length); } catch (IOException e) {} return null; } diff --git a/test/langtools/tools/javac/options/T7022337.java b/test/langtools/tools/javac/options/T7022337.java index 450a623edc3..7ca34cca4fe 100644 --- a/test/langtools/tools/javac/options/T7022337.java +++ b/test/langtools/tools/javac/options/T7022337.java @@ -94,11 +94,8 @@ public class T7022337 extends JavacTestingAbstractProcessor { void generate(String name) { try { JavaFileObject fo = filer.createSourceFile(name); - Writer out = fo.openWriter(); - try { + try (Writer out = fo.openWriter()) { out.write("class " + name + " { }"); - } finally { - out.close(); } } catch (IOException e) { throw new Error(e); diff --git a/test/langtools/tools/javac/parser/ExtraSemiTest.java b/test/langtools/tools/javac/parser/ExtraSemiTest.java index 2c8753bb6d2..c3445bf3314 100644 --- a/test/langtools/tools/javac/parser/ExtraSemiTest.java +++ b/test/langtools/tools/javac/parser/ExtraSemiTest.java @@ -90,12 +90,9 @@ public class ExtraSemiTest { String readFile(File f) throws IOException { int len = (int) f.length(); byte[] data = new byte[len]; - DataInputStream in = new DataInputStream(new FileInputStream(f)); - try { + try (DataInputStream in = new DataInputStream(new FileInputStream(f))) { in.readFully(data); return new String(data); - } finally { - in.close(); } } } diff --git a/test/langtools/tools/javac/preview/PreviewErrors.java b/test/langtools/tools/javac/preview/PreviewErrors.java index b3d91ec0514..87fb242ffa3 100644 --- a/test/langtools/tools/javac/preview/PreviewErrors.java +++ b/test/langtools/tools/javac/preview/PreviewErrors.java @@ -39,6 +39,7 @@ */ import java.io.IOException; +import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; @@ -404,7 +405,9 @@ public class PreviewErrors extends ComboInstance { if (testClass == null) { throw new IllegalStateException("Cannot find Test.class"); } - cf = ClassFile.read(testClass.openInputStream()); + try (InputStream input = testClass.openInputStream()) { + cf = ClassFile.read(input); + } } catch (IOException | ConstantPoolException ex) { throw new IllegalStateException(ex); } diff --git a/test/langtools/tools/javac/processing/6350124/HelloWorldAP.java b/test/langtools/tools/javac/processing/6350124/HelloWorldAP.java index cfa9aa50988..84d843023bd 100644 --- a/test/langtools/tools/javac/processing/6350124/HelloWorldAP.java +++ b/test/langtools/tools/javac/processing/6350124/HelloWorldAP.java @@ -46,8 +46,7 @@ public class HelloWorldAP extends AbstractProcessor { boolean ret = true; if(!renv.processingOver() && !DONE) { msgr.printNote("running process to create HelloWorld."); - try { - Writer pw = filer.createSourceFile("HelloWorld").openWriter(); + try (Writer pw = filer.createSourceFile("HelloWorld").openWriter()) { pw.write("public class HelloWorld {\n"); pw.write(" public static void main (String argv[]) {\n"); pw.write(" System.out.println(\"Hello apt world.\");\n"); @@ -56,13 +55,11 @@ public class HelloWorldAP extends AbstractProcessor { pw.flush(); pw.close(); - OutputStream os = filer.createClassFile("HelloWorldAP").openOutputStream(); // the easiest way to create a class file is to copy another one - InputStream is = getClass().getResourceAsStream("HelloWorldAP.class"); - copy(is, os); - is.close(); - os.flush(); - os.close(); + try (OutputStream os = filer.createClassFile("HelloWorldAP").openOutputStream(); + InputStream is = getClass().getResourceAsStream("HelloWorldAP.class")) { + copy(is, os); + } DONE=true; } catch (IOException ioe) { diff --git a/test/langtools/tools/javac/processing/6413690/T6413690.java b/test/langtools/tools/javac/processing/6413690/T6413690.java index ea2f40718b2..f0a01d599ef 100644 --- a/test/langtools/tools/javac/processing/6413690/T6413690.java +++ b/test/langtools/tools/javac/processing/6413690/T6413690.java @@ -53,11 +53,11 @@ public class T6413690 extends JavacTestingAbstractProcessor { Set supers = roundEnvironment.getElementsAnnotatedWith(testMe); try { for (Element sup : supers) { - Writer sub = filer.createSourceFile(sup.getSimpleName() + "_GENERATED").openWriter(); - sub.write(String.format("class %s_GENERATED extends %s {}", - sup.getSimpleName(), - ((TypeElement)sup).getQualifiedName())); - sub.close(); + try (Writer sub = filer.createSourceFile(sup.getSimpleName() + "_GENERATED").openWriter()) { + sub.write(String.format("class %s_GENERATED extends %s {}", + sup.getSimpleName(), + ((TypeElement)sup).getQualifiedName())); + } } } catch (IOException ex) { throw new RuntimeException(ex); diff --git a/test/langtools/tools/javac/processing/6499119/ClassProcessor.java b/test/langtools/tools/javac/processing/6499119/ClassProcessor.java index 824b6f51844..4c432318b78 100644 --- a/test/langtools/tools/javac/processing/6499119/ClassProcessor.java +++ b/test/langtools/tools/javac/processing/6499119/ClassProcessor.java @@ -78,39 +78,18 @@ public class ClassProcessor extends JavacTestingAbstractProcessor { pkgInfo = new File(System.getProperty("test.classes"), "foo/package-info.class"); byte[] bytes = new byte[(int) pkgInfo.length()]; - DataInputStream in = null; - try { - in = new DataInputStream(new FileInputStream(pkgInfo)); + try (DataInputStream in = new DataInputStream(new FileInputStream(pkgInfo))) { in.readFully(bytes); } catch (IOException ioe) { error("Couldn't read package info file: " + ioe); - } finally { - if(in != null) { - try { - in.close(); - } catch (IOException e) { - error("InputStream closing failed: " + e); - } - } } - OutputStream out = null; - try { - if (kind.equals("java")) - out = filer.createSourceFile("foo.package-info").openOutputStream(); - else - out = filer.createClassFile("foo.package-info").openOutputStream(); + try (OutputStream out = kind.equals("java") ? + filer.createSourceFile("foo.package-info").openOutputStream() : + filer.createClassFile("foo.package-info").openOutputStream()) { out.write(bytes, 0, bytes.length); } catch (IOException ioe) { error("Couldn't create package info file: " + ioe); - } finally { - if(out != null) { - try { - out.close(); - } catch (IOException e) { - error("OutputStream closing failed: " + e); - } - } } } diff --git a/test/langtools/tools/javac/processing/6634138/T6634138.java b/test/langtools/tools/javac/processing/6634138/T6634138.java index 40ef9160d66..872192d51ec 100644 --- a/test/langtools/tools/javac/processing/6634138/T6634138.java +++ b/test/langtools/tools/javac/processing/6634138/T6634138.java @@ -55,22 +55,16 @@ public class T6634138 extends JavacTestingAbstractProcessor { if (roundEnvironment.processingOver()) { System.out.println("Writing out source files."); try { - PrintWriter pw = new PrintWriter(filer.createSourceFile("foo.WrittenAfterProcessing").openWriter()); - try { + try (PrintWriter pw = new PrintWriter(filer.createSourceFile("foo.WrittenAfterProcessing").openWriter())) { pw.println("package foo;"); pw.println("public class WrittenAfterProcessing {"); pw.println(" public WrittenAfterProcessing() {super();}"); pw.println("}"); - } finally { - pw.close(); } - pw = new PrintWriter(filer.createSourceFile("foo.package-info").openWriter()); - try { + try (PrintWriter pw = new PrintWriter(filer.createSourceFile("foo.package-info").openWriter())) { pw.println("@Deprecated"); pw.println("package foo;"); - } finally { - pw.close(); } } catch(IOException io) { throw new RuntimeException(io); diff --git a/test/langtools/tools/javac/processing/T6439826.java b/test/langtools/tools/javac/processing/T6439826.java index 661c8161bab..846d77c3a7e 100644 --- a/test/langtools/tools/javac/processing/T6439826.java +++ b/test/langtools/tools/javac/processing/T6439826.java @@ -84,10 +84,8 @@ public class T6439826 extends AbstractProcessor { private void writeBadFile() { Filer filer = processingEnv.getFiler(); Messager messager = processingEnv.getMessager(); - try { - Writer out = filer.createSourceFile("Foo").openWriter(); + try (Writer out = filer.createSourceFile("Foo").openWriter()) { out.write("class Foo #"); // write a file that generates a scanner error - out.close(); } catch (IOException e) { messager.printError(e.toString()); } diff --git a/test/langtools/tools/javac/processing/T6920317.java b/test/langtools/tools/javac/processing/T6920317.java index d332ca4f041..0321a28b548 100644 --- a/test/langtools/tools/javac/processing/T6920317.java +++ b/test/langtools/tools/javac/processing/T6920317.java @@ -406,40 +406,20 @@ public class T6920317 { /** Read a file. */ byte[] read(File file) { byte[] bytes = new byte[(int) file.length()]; - DataInputStream in = null; - try { - in = new DataInputStream(new FileInputStream(file)); + try (DataInputStream in = new DataInputStream(new FileInputStream(file))) { in.readFully(bytes); } catch (IOException e) { error("Error reading file: " + e); - } finally { - if (in != null) { - try { - in.close(); - } catch (IOException e) { - error("Error closing file: " + e); - } - } } return bytes; } /** Write a file. */ void write(JavaFileObject file, byte[] bytes) { - OutputStream out = null; - try { - out = file.openOutputStream(); + try (OutputStream out = file.openOutputStream()) { out.write(bytes, 0, bytes.length); } catch (IOException e) { error("Error writing file: " + e); - } finally { - if (out != null) { - try { - out.close(); - } catch (IOException e) { - error("Error closing file: " + e); - } - } } } diff --git a/test/langtools/tools/javac/processing/TestWarnErrorCount.java b/test/langtools/tools/javac/processing/TestWarnErrorCount.java index 13f2009d7b8..1ea2b803609 100644 --- a/test/langtools/tools/javac/processing/TestWarnErrorCount.java +++ b/test/langtools/tools/javac/processing/TestWarnErrorCount.java @@ -322,14 +322,11 @@ public class TestWarnErrorCount extends JavacTestingAbstractProcessor { void generate(String name, boolean error, boolean warn) { try { JavaFileObject fo = filer.createSourceFile(name); - Writer out = fo.openWriter(); - try { + try (Writer out = fo.openWriter()) { out.write("class " + name + " {\n" + (warn ? " void m() throws Exception { try (AutoCloseable ac = null) { } }" : "") + (error ? " ERROR\n" : "") + "}\n"); - } finally { - out.close(); } } catch (IOException e) { throw new Error(e); diff --git a/test/langtools/tools/javac/processing/errors/TestSuppression.java b/test/langtools/tools/javac/processing/errors/TestSuppression.java index 7b332db76df..0eb5b73a9eb 100644 --- a/test/langtools/tools/javac/processing/errors/TestSuppression.java +++ b/test/langtools/tools/javac/processing/errors/TestSuppression.java @@ -232,9 +232,9 @@ public class TestSuppression { private void writeSource(String name, String text) { try { JavaFileObject fo = f.createSourceFile(name); - Writer out = fo.openWriter(); - out.write(text); - out.close(); + try (Writer out = fo.openWriter()) { + out.write(text); + } } catch (IOException e) { m.printError(e.toString()); } diff --git a/test/langtools/tools/javac/processing/filer/TestGetResource.java b/test/langtools/tools/javac/processing/filer/TestGetResource.java index 6618bc58c6d..073757d1217 100644 --- a/test/langtools/tools/javac/processing/filer/TestGetResource.java +++ b/test/langtools/tools/javac/processing/filer/TestGetResource.java @@ -65,10 +65,10 @@ public class TestGetResource extends JavacTestingAbstractProcessor { String phase = options.get("phase"); if (phase.equals("write")) { - PrintWriter pw = - new PrintWriter(filer.createResource(CLASS_OUTPUT, PKG, RESOURCE_NAME).openWriter()); - pw.print(CONTENTS); - pw.close(); + try (PrintWriter pw = + new PrintWriter(filer.createResource(CLASS_OUTPUT, PKG, RESOURCE_NAME).openWriter())) { + pw.print(CONTENTS); + } } else if (phase.equals("read")) { String contents = filer.getResource(CLASS_OUTPUT, PKG, diff --git a/test/langtools/tools/javac/processing/filer/TestLastRound.java b/test/langtools/tools/javac/processing/filer/TestLastRound.java index 9454af3136e..0e66b5ada55 100644 --- a/test/langtools/tools/javac/processing/filer/TestLastRound.java +++ b/test/langtools/tools/javac/processing/filer/TestLastRound.java @@ -46,9 +46,9 @@ public class TestLastRound extends JavacTestingAbstractProcessor { if (roundEnv.processingOver()) { try { JavaFileObject fo = filer.createSourceFile("LastRound.java"); - Writer out = fo.openWriter(); - out.write("class LastRound { }"); - out.close(); + try (Writer out = fo.openWriter()) { + out.write("class LastRound { }"); + } } catch (IOException e) { } } diff --git a/test/langtools/tools/javac/processing/model/element/TestMissingElement2/Generator.java b/test/langtools/tools/javac/processing/model/element/TestMissingElement2/Generator.java index abb91b40c65..5e91916a4bf 100644 --- a/test/langtools/tools/javac/processing/model/element/TestMissingElement2/Generator.java +++ b/test/langtools/tools/javac/processing/model/element/TestMissingElement2/Generator.java @@ -61,8 +61,7 @@ public class Generator extends JavacTestingAbstractProcessor { void createFile(TypeElement e) { try { JavaFileObject fo = filer.createSourceFile(e.getSimpleName()); - Writer out = fo.openWriter(); - try { + try (Writer out = fo.openWriter()) { switch (e.getKind()) { case CLASS: out.write("import java.util.*;\n"); @@ -83,8 +82,6 @@ public class Generator extends JavacTestingAbstractProcessor { out.write("}\n"); break; } - } finally { - out.close(); } } catch (IOException ex) { messager.printError("problem writing file: " + ex); diff --git a/test/langtools/tools/javac/processing/model/element/TestNames.java b/test/langtools/tools/javac/processing/model/element/TestNames.java index 50091043c42..602a7c1cfb7 100644 --- a/test/langtools/tools/javac/processing/model/element/TestNames.java +++ b/test/langtools/tools/javac/processing/model/element/TestNames.java @@ -76,11 +76,9 @@ public class TestNames extends JavacTestingAbstractProcessor { failed = true; - try { - // Force another round with a new context - PrintWriter pw = new PrintWriter(filer.createSourceFile("Foo").openWriter()); + // Force another round with a new context + try (PrintWriter pw = new PrintWriter(filer.createSourceFile("Foo").openWriter())) { pw.println("public class Foo {}"); - pw.close(); } catch (IOException ioe) { throw new RuntimeException(); } diff --git a/test/langtools/tools/javac/processing/model/util/elements/TestGetConstantExpression.java b/test/langtools/tools/javac/processing/model/util/elements/TestGetConstantExpression.java index 2ae7ea0ae55..a9827b2aacc 100644 --- a/test/langtools/tools/javac/processing/model/util/elements/TestGetConstantExpression.java +++ b/test/langtools/tools/javac/processing/model/util/elements/TestGetConstantExpression.java @@ -65,39 +65,34 @@ public class TestGetConstantExpression extends JavacTestingAbstractProcessor { // Generate source code with various constant values and // make sure it compiles. - try { - PrintWriter pw = new PrintWriter(filer.createSourceFile("ConstantTest").openWriter()); - try { - Boolean[] booleans = {true, false}; - Byte[] bytes = {Byte.MIN_VALUE, -1, 0, 1, Byte.MAX_VALUE}; - Short[] shorts = {Short.MIN_VALUE, -1, 0, 1, Short.MAX_VALUE}; - Integer[] ints = {Integer.MIN_VALUE, -1, 0, 1, Integer.MAX_VALUE}; - Long[] longs = {Long.MIN_VALUE, -1L, 0L,1L, Long.MAX_VALUE}; - Character[] chars = {Character.MIN_VALUE, ' ', '\t', 'a', 'b', 'c', '~', Character.MAX_VALUE}; - Float[] floats = {Float.NaN, Float.NEGATIVE_INFINITY, -1.0f, -0.0f, 0.0f, 1.0f, Float.POSITIVE_INFINITY}; - Double[] doubles = {Double.NaN, Double.NEGATIVE_INFINITY, -1.0, -0.0, 0.0, 1.0, Double.POSITIVE_INFINITY}; + try (PrintWriter pw = new PrintWriter(filer.createSourceFile("ConstantTest").openWriter())) { + Boolean[] booleans = {true, false}; + Byte[] bytes = {Byte.MIN_VALUE, -1, 0, 1, Byte.MAX_VALUE}; + Short[] shorts = {Short.MIN_VALUE, -1, 0, 1, Short.MAX_VALUE}; + Integer[] ints = {Integer.MIN_VALUE, -1, 0, 1, Integer.MAX_VALUE}; + Long[] longs = {Long.MIN_VALUE, -1L, 0L,1L, Long.MAX_VALUE}; + Character[] chars = {Character.MIN_VALUE, ' ', '\t', 'a', 'b', 'c', '~', Character.MAX_VALUE}; + Float[] floats = {Float.NaN, Float.NEGATIVE_INFINITY, -1.0f, -0.0f, 0.0f, 1.0f, Float.POSITIVE_INFINITY}; + Double[] doubles = {Double.NaN, Double.NEGATIVE_INFINITY, -1.0, -0.0, 0.0, 1.0, Double.POSITIVE_INFINITY}; - pw.println("class ConstantTest {"); - pw.println(String.format(" private static boolean[] booleans = {%s};", - printConstants(booleans))); - pw.println(String.format(" private static byte[] bytes = {%s};", - printConstants(bytes))); - pw.println(String.format(" private static short[] shorts = {%s};", - printConstants(shorts))); - pw.println(String.format(" private static int[] ints = {%s};", - printConstants(ints))); - pw.println(String.format(" private static long[] longs = {%s};", - printConstants(longs))); - pw.println(String.format(" private static char[] chars = {%s};", - printConstants(chars))); - pw.println(String.format(" private static float[] floats = {%s};", - printConstants(floats))); - pw.println(String.format(" private static double[] doubles = {%s};", - printConstants(doubles))); - pw.println("}"); - } finally { - pw.close(); - } + pw.println("class ConstantTest {"); + pw.println(String.format(" private static boolean[] booleans = {%s};", + printConstants(booleans))); + pw.println(String.format(" private static byte[] bytes = {%s};", + printConstants(bytes))); + pw.println(String.format(" private static short[] shorts = {%s};", + printConstants(shorts))); + pw.println(String.format(" private static int[] ints = {%s};", + printConstants(ints))); + pw.println(String.format(" private static long[] longs = {%s};", + printConstants(longs))); + pw.println(String.format(" private static char[] chars = {%s};", + printConstants(chars))); + pw.println(String.format(" private static float[] floats = {%s};", + printConstants(floats))); + pw.println(String.format(" private static double[] doubles = {%s};", + printConstants(doubles))); + pw.println("}"); } catch(IOException io) { throw new RuntimeException(io); } diff --git a/test/langtools/tools/javac/processing/model/util/elements/doccomments/TestDocComments.java b/test/langtools/tools/javac/processing/model/util/elements/doccomments/TestDocComments.java index 9ef5a799619..6011111897d 100644 --- a/test/langtools/tools/javac/processing/model/util/elements/doccomments/TestDocComments.java +++ b/test/langtools/tools/javac/processing/model/util/elements/doccomments/TestDocComments.java @@ -189,11 +189,8 @@ public class TestDocComments extends JavacTestingAbstractProcessor { try { JavaFileObject fo = filer.createSourceFile(curr); - Writer out = fo.openWriter(); - try { + try (Writer out = fo.openWriter()) { out.write(text.toString()); - } finally { - out.close(); } } catch (IOException e) { throw new Error(e); diff --git a/test/langtools/tools/javac/processing/options/testPrintProcessorInfo/Test.java b/test/langtools/tools/javac/processing/options/testPrintProcessorInfo/Test.java index a4b6f5a5c74..8fa85087dae 100644 --- a/test/langtools/tools/javac/processing/options/testPrintProcessorInfo/Test.java +++ b/test/langtools/tools/javac/processing/options/testPrintProcessorInfo/Test.java @@ -57,15 +57,8 @@ public class Test extends JavacTestingAbstractProcessor { void generateSource(String name) { String text = "class " + name + " { }\n"; - - // avoid try-with-resources so test can be run on older builds - try { - Writer out = filer.createSourceFile(name).openWriter(); - try { - out.write(text); - } finally { - out.close(); - } + try (Writer out = filer.createSourceFile(name).openWriter()) { + out.write(text); } catch (IOException e) { throw new Error(e); } diff --git a/test/langtools/tools/javac/processing/rounds/BaseClassesNotReRead.java b/test/langtools/tools/javac/processing/rounds/BaseClassesNotReRead.java index 4d785fa49d4..91935a52b6e 100644 --- a/test/langtools/tools/javac/processing/rounds/BaseClassesNotReRead.java +++ b/test/langtools/tools/javac/processing/rounds/BaseClassesNotReRead.java @@ -91,7 +91,6 @@ public class BaseClassesNotReRead extends AbstractProcessor { Filer filer = processingEnv.getFiler(); try (Writer out = filer.createSourceFile(name).openWriter()) { out.write(code); - out.close(); } catch (IOException e) { processingEnv.getMessager().printError(e.toString()); } diff --git a/test/langtools/tools/javac/processing/werror/WErrorGen.java b/test/langtools/tools/javac/processing/werror/WErrorGen.java index a8bfdea8e7c..b4e35fb9171 100644 --- a/test/langtools/tools/javac/processing/werror/WErrorGen.java +++ b/test/langtools/tools/javac/processing/werror/WErrorGen.java @@ -47,9 +47,9 @@ public class WErrorGen extends JavacTestingAbstractProcessor { if (++round == 1) { try { JavaFileObject fo = filer.createSourceFile("Gen"); - Writer out = fo.openWriter(); - out.write("import java.util.*; class Gen { List l; }"); - out.close(); + try (Writer out = fo.openWriter()) { + out.write("import java.util.*; class Gen { List l; }"); + } } catch (IOException e) { } } diff --git a/test/langtools/tools/javac/sealed/ValidateJarWithSealedAndRecord.java b/test/langtools/tools/javac/sealed/ValidateJarWithSealedAndRecord.java index 07cc71d5092..1c70774b0c0 100644 --- a/test/langtools/tools/javac/sealed/ValidateJarWithSealedAndRecord.java +++ b/test/langtools/tools/javac/sealed/ValidateJarWithSealedAndRecord.java @@ -45,9 +45,9 @@ public class ValidateJarWithSealedAndRecord { } void writeFile(String f, String contents) throws IOException { - PrintStream s = new PrintStream(new FileOutputStream(f)); - s.println(contents); - s.close(); + try (PrintStream s = new PrintStream(new FileOutputStream(f))) { + s.println(contents); + } } private static final ToolProvider JAR_TOOL = ToolProvider.findFirst("jar").orElseThrow(() -> new RuntimeException("jar tool not found")); diff --git a/test/langtools/tools/javac/switchexpr/SwitchExpressionNoValue.java b/test/langtools/tools/javac/switchexpr/SwitchExpressionNoValue.java index 4045f785f98..7d0e1b1d099 100644 --- a/test/langtools/tools/javac/switchexpr/SwitchExpressionNoValue.java +++ b/test/langtools/tools/javac/switchexpr/SwitchExpressionNoValue.java @@ -42,6 +42,7 @@ import combo.ComboInstance; import combo.ComboParameter; import combo.ComboTask; import combo.ComboTestHelper; +import java.io.InputStream; import java.lang.reflect.InvocationTargetException; import java.nio.file.Path; import java.nio.file.Paths; @@ -111,7 +112,10 @@ public class SwitchExpressionNoValue extends ComboInstance findClass(String name) throws ClassNotFoundException { if ("Test".equals(name)) { diff --git a/test/langtools/tools/javac/tree/TreePosRoundsTest.java b/test/langtools/tools/javac/tree/TreePosRoundsTest.java index 1f3ddc30a81..7ba12aa88e2 100644 --- a/test/langtools/tools/javac/tree/TreePosRoundsTest.java +++ b/test/langtools/tools/javac/tree/TreePosRoundsTest.java @@ -120,11 +120,8 @@ public class TreePosRoundsTest extends AbstractProcessor { try { JavaFileObject fo = filer.createSourceFile(name); - Writer out = fo.openWriter(); - try { + try (Writer out = fo.openWriter()) { out.write(text.toString()); - } finally { - out.close(); } } catch (IOException e) { throw new Error(e);