Try with resources
- Eclipse: Oxygen
- Java: 1.8
The try with resources is a command that whenever we allocate some resources, for example, Assigning a resource to take input from the Scanner class. If the user fails to close the resource, then it leads to a resource leak which could prove dangerous to the execution of a program. Hence after implementing the same in a try block, we can avoid the resource leak.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println("Enter a int value"); int x = scan.nextInt(); System.out.println(x); scan.close(); } } |
Whenever we are making use of data resources stream for example scanner class or Buffered class it needs to be closed after the program is finished with it. So, in the following program, the closing of resources is done by itself, try.
Inside this parenthesis, we are creating an object. This object is a resource that needs to be closed else we will get a warning.
try(BufferedWriter bw = new BufferedWriter(new FileWriter(file,true))
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
public class Main { public static void main(String[] args) { { File file = new File("studyeasy"); file.mkdir(); file = new File("studyeasy\\team.txt"); try(BufferedWriter bw = new BufferedWriter(new FileWriter(file,true))){ bw.write("Chaand"); bw.newLine(); bw.write("Shabaz"); bw.newLine(); bw.write("Salim"); bw.newLine(); bw.write("Praful"); bw.newLine(); bw.write("Aarti"); System.out.println("Wrting onto the file completed"); bw.close(); } catch (IOException e) { System.out.println("error occured, while creating writing onto file"); } } } } |
Contributed by: Poonam Tomar