Reputation: 890
I am using BufferedReader to read file in java.
Following is the code snippet:
String line;
br = new BufferedReader(new FileReader("file1.txt"));
while ((line = br.readLine()) != null) {
System.out.println(line);
}
//Here I want to open file named "file2.txt".
As mentioned in the code snipped above, i want to now open a new file.
What is the best way to do so ?
Should i first close br using br.close, and then again initialise br or what ?
P.S.: I am new to Java.
Upvotes: 1
Views: 2072
Reputation: 136152
I would make a method and call it twice
void readFile(String fileName) throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
...
}
}
note that BufferedReader
instance br
will be closed automatically and make sure that you are using JDK 7 for this
Upvotes: 2
Reputation: 68715
Creating a method will make your code modular and easy to use. This will lead to re-usability of code and ease of understanding. Here is the sample code:
public static void main(String args[]) {
readFile("C:\\sample.txt");
}
public static void readFile(String filename) {
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(filename));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Upvotes: 4
Reputation: 9721
Yes, close it first, but use this pattern ...
BufferedReader br = null;
String line;
try {
br = new BufferedReader(new FileReader("file1.txt"));
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
finally {
if (br != null) br.close();
}
//Here I want to open file named "file2.txt".
Or, the try-with-resources approach (semantically equivalent to the above) ...
String line;
try (BufferedReader br = new BufferedReader(new FileReader("file1.txt")) {
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
//Here I want to open file named "file2.txt".
Upvotes: 0