How do we read .txt files in Java using Java 7 try-catch with resources?
Is there a way you can reduce the lines of code using the new try-catch
with resources in Java 7. My code is the following and I'd appreciate if
someone can guide me on making it much simpler and efficient by using
try-catch with resources available to us in Java 7.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
public class ReadFile {
public static void main (String[] args) {
String name = "text.txt";
File f = new File (name);
BufferedReader br = null;
try {
FileReader fr = new FileReader(f);
br = new BufferedReader(fr);
String output;
int count = 0;
while ( (output = br.readLine()) != null) {
System.out.println(output);
count++;
}
System.out.println("Number of lines: " + count);
} catch (FileNotFoundException e) {
System.out.println("Can't find file");
} catch (IOException e) {
System.out.println("Unable to read file");
}
finally {
try {
br.close();
} catch (IOException e) {
System.out.println("Unable to close file");
} catch (NullPointerException ex){
// File was not opened
}
}
}
}
No comments:
Post a Comment