We can put more than one resource within a single try statement.
import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class Main { public static void main(String args[]) throws IOException { int i;//ww w . j av a 2s.c o m // Open and manage two files via the try statement. try (FileInputStream fin = new FileInputStream("Main.java"); FileOutputStream fout = new FileOutputStream("Test.java")) { do { i = fin.read(); if (i != -1) fout.write(i); } while (i != -1); } catch (IOException e) { System.out.println("I/O Error: " + e); } } }
import java.io.BufferedOutputStream; import java.io.DataOutputStream; import java.io.FileOutputStream; public class Main { public static void main(String[] args) { try (FileOutputStream fos = new FileOutputStream("out.log"); BufferedOutputStream bos = new BufferedOutputStream(fos); DataOutputStream dos = new DataOutputStream(bos)) { dos.writeUTF("This is being written"); // let's throw an exception and dos.close();/*from w w w .j a v a 2 s . c o m*/ } catch (Exception e) { System.out.println("Some bad exception happened "); } } }