Advertisement
yo2man

Tutorial 39 Try-With-Resources

May 24th, 2015
238
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.70 KB | None | 0 0
  1. //Tutorial 39 Try-With-Resources
  2. //this is a Java 7 language feature
  3. //this feature gets rid of the nested tri-catch blocks all over the place in Reading Files with File Reader tutorial
  4.  
  5. //App.java
  6. class Temp implements AutoCloseable { //step 1. AutoCloseable interface just specifies that you class should have a method called close
  7.  
  8.     @Override                        //step 1. now we have the close method here
  9.     public void close() throws Exception {
  10.         System.out.println("Closing!");
  11.         throw new Exception("oh no!")
  12.     }
  13.    
  14. }
  15. public class App {
  16.  
  17.     public static void main(String[] args) {
  18.         try(Temp temp = new Temp()){ //since Java 7 when can put it in try( ) like while( )
  19.        
  20.         } catch (Exception e) {
  21.             // TODO Auto-generated catch block
  22.             e.printStackTrace();
  23.         }
  24.     }
  25.  
  26. }
  27. //---------------------------------------------------------------------------------------------------------------------------------------
  28. /*Run Results:
  29. Closing!
  30. java.lang.Exception: oh no!
  31.     at Temp.close(App.java:10)
  32.     at App.main(App.java:19)
  33. */
  34.  
  35.  
  36.  
  37.  
  38. //How this works in regards to text files:
  39. //App2.java
  40. import java.io.BufferedReader;
  41. import java.io.File;
  42. import java.io.FileNotFoundException;
  43. import java.io.FileReader;
  44. import java.io.IOException;
  45.  
  46.  
  47. public class App2 {
  48.     public static void main(String[] args){
  49.         File file = new File("text.txt");
  50.  
  51.         try(BufferedReader br = new BufferedReader( new FileReader(file))){
  52.            
  53.         } catch (FileNotFoundException e) {
  54.             System.out.println("Can't find file: " + file.toString());
  55.         } catch (IOException e) {
  56.             System.out.println("Unable to read file: " + file.toString());
  57.         }
  58.    
  59.        
  60.     }
  61. }
  62. //this is much much more succinct then the mess we had last tutorial
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement