Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Tutorial 39 Try-With-Resources
- //this is a Java 7 language feature
- //this feature gets rid of the nested tri-catch blocks all over the place in Reading Files with File Reader tutorial
- //App.java
- class Temp implements AutoCloseable { //step 1. AutoCloseable interface just specifies that you class should have a method called close
- @Override //step 1. now we have the close method here
- public void close() throws Exception {
- System.out.println("Closing!");
- throw new Exception("oh no!")
- }
- }
- public class App {
- public static void main(String[] args) {
- try(Temp temp = new Temp()){ //since Java 7 when can put it in try( ) like while( )
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- //---------------------------------------------------------------------------------------------------------------------------------------
- /*Run Results:
- Closing!
- java.lang.Exception: oh no!
- at Temp.close(App.java:10)
- at App.main(App.java:19)
- */
- //How this works in regards to text files:
- //App2.java
- import java.io.BufferedReader;
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.io.FileReader;
- import java.io.IOException;
- public class App2 {
- public static void main(String[] args){
- File file = new File("text.txt");
- try(BufferedReader br = new BufferedReader( new FileReader(file))){
- } catch (FileNotFoundException e) {
- System.out.println("Can't find file: " + file.toString());
- } catch (IOException e) {
- System.out.println("Unable to read file: " + file.toString());
- }
- }
- }
- //this is much much more succinct then the mess we had last tutorial
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement