user1599964
user1599964

Reputation: 890

Reading different file one after another using BufferedReader in Java

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

Answers (4)

Evgeniy Dorofeev
Evgeniy Dorofeev

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

Juned Ahsan
Juned Ahsan

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

xagyg
xagyg

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

Chris
Chris

Reputation: 5654

File I/O operations internally use Decorator pattern. So, .close() on the outermost object should close all internal I/Os

Upvotes: 0

Related Questions