Remember when we learnt how to read a file using FileReader?
Well, I told you and you’d agree that that tutorial was a bit difficult. There
were so many exceptions that we had to throw and catch and the program did not
look neat in any way whatsoever.
In Java 7, Oracle introduced a new feature called “try with
resources.” What try with resources means is that you can write the code that
was originally inside the curly braces of the try block of the try-catch block
inside round brackets just after the word “try”, but before the opening curly
brace of the try block.
However, remember that when opening the file, we created a
file object to which we passed the address of the file to its constructor like
this:
File file = new File (“C:/Users/Mukami/Desktop/Document1.txt”);
Then, we created a FileReader object that would read the file
and then passed the file object to its constructor like this:
FileReader fileReader1 = new FileReader(file);
Then, we created a BufferedReader object to read the file
line by line and passed the FileReader object to its constructor like this:
BufferedReader bufferedReader1 = new
BufferedReader(fileReader1);
All the above steps could be done in one line like this:
BufferedReader bufferedReader1 = new BufferedReader(new
FileReader(file));
So in try with resources, what we do is surround the above
line with round braces like this and place it just after the try keyword.
try(BufferedReader bufferedReader1 = new BufferedReader(new
FileReader(file))) {
}
Then, we surround try with the catch blocks like this:
try(BufferedReader bufferedReader1 = new BufferedReader(new
FileReader(file))) {
} catch (FileNotFoundException e) {
System.out.println(“Could
not open the file”);
} catch (IOException e) {
System.out.println(“Cannot
read the file”);
}
Now, we can add the functionality to read the file within the
try block like this:
try(BufferedReader bufferedReader1 = new BufferedReader(new
FileReader(file))) {
String line;
while((line
= bufferedReader1.readLine()) != null) {
System.out.println(line);
}
} catch (FileNotFoundException e) {
System.out.println(“Could not find
file”);
} catch (IOException e) {
System.out.println
(“Cannot read the file”);
}Figure 1: Reading a text file using the try with resources Java syntax
Now we have a program that reads and closes a file. Remember
that in the previous tutorial, we had to call bufferedReader1.close(). However,
with try with resources, Java will automatically close the file handle for you.
This really makes your code neater than in the previous tutorial.
Note that you can use try with resources anywhere where you
would use a try-catch block, and this doesn’t necessarily mean that it can only
be used when we want to open and read contents of a file. This was just an
example.
No comments:
Post a Comment