Using BufferedReader to read Text File
Asked Answered
G

10

34

I'm having problems with using the BufferedReader

I want to print the 6 lines of a text file:

public class Reader {

public static void main(String[]args) throws IOException{
    
    FileReader in = new FileReader("C:/test.txt");
    BufferedReader br = new BufferedReader(in);
    
    while (br.readLine() != null) {
        System.out.println(br.readLine());
    }
    in.close();
    
}

Now from what I can gather every time I call the readLine() method it automatically advances to the next line.

So I can't use the condition br.readLine() != null since it'll already advance it one line and I get the output:

Line 2
Line 4
Line 6

What Condition do I use to check if there is still a new line in the text field?

Geranium answered 19/4, 2013 at 12:28 Comment(0)
A
80

This is the problem:

while (br.readLine() != null) {
    System.out.println(br.readLine());
}

You've got two calls to readLine - the first only checks that there's a line (but reads it and throws it away) and the second reads the next line. You want:

String line;
while ((line = br.readLine()) != null) {
    System.out.println(line);
}

Now we're only calling readLine() once per loop iteration, and using the line that we've read both for the "have we finished?" and "print out the line" parts.

Alage answered 19/4, 2013 at 12:31 Comment(2)
...except don't mix assignment, a test, and loop control on one line like this. I mean just don't. Please? :DEdita
@tekHedd: I don't for most code - but this particular pattern is so common that it doesn't cause me any concern at all. (And heck, for loops almost always have assignment, test and loop control in a single line...) I'd rather do this than call readLine() in two different places, or other ways of avoiding this specific pattern. (In modern C#, pattern matching allows while (reader.ReadLine() is string line) which is rather nicer... not sure if modern Java has the same construct. But it's fundamentally very similar...)Alage
B
6

You read line through while loop and through the loop you read the next line ,so just read it in while loop

 String s;
 while ((s=br.readLine()) != null) {
     System.out.println(s);
  }
Berrios answered 19/4, 2013 at 12:31 Comment(0)
S
5

You can assign the result of br.readLine() to a variable and use that both for processing and for checking, like so:

String line = br.readLine();
while (line != null) { // You might also want to check for empty?
    System.out.println(line);
    line = br.readLine();
}
Servomotor answered 19/4, 2013 at 12:31 Comment(0)
P
2

Use try with resources. this will automatically close the resources.

try (BufferedReader br = new BufferedReader(new FileReader("C:/test.txt"))) {
    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
} catch (Exception e) {

}
Postrider answered 9/6, 2020 at 16:21 Comment(0)
W
1
private void readFile() throws Exception {
      AsynchronousFileChannel input=AsynchronousFileChannel.open(Paths.get("E:/dicom_server_storage/abc.txt"),StandardOpenOption.READ);
      ByteBuffer buffer=ByteBuffer.allocate(1024);
      input.read(buffer,0,null,new CompletionHandler<Integer,Void>(){
        @Override public void completed(    Integer result,    Void attachment){
          System.out.println("Done reading the file.");
        }
        @Override public void failed(    Throwable exc,    Void attachment){
          System.err.println("An error occured:" + exc.getMessage());
        }
      }
    );
      System.out.println("This thread keeps on running");
      Thread.sleep(100);
    }
Wadsworth answered 9/9, 2015 at 13:14 Comment(0)
S
0

Maybe you mean this:

public class Reader {

public static void main(String[]args) throws IOException{

    FileReader in = new FileReader("C:/test.txt");
    BufferedReader br = new BufferedReader(in);
    String line = br.readLine();
    while (line!=null) {
        System.out.println(line);
        line = br.readLine();
    }
    in.close();

}
Sabba answered 19/4, 2013 at 12:31 Comment(0)
F
0

Try:

String text= br.readLine();
while (text != null) 
{
  System.out.println(text);
  text=br.readLine();
}
in.close();
Fascine answered 19/4, 2013 at 12:31 Comment(0)
F
0

or

public String getFileStream(final String inputFile) {
        String result = "";
        Scanner s = null;

        try {
            s = new Scanner(new BufferedReader(new FileReader(inputFile)));
            while (s.hasNext()) {
                result = result + s.nextLine();
            }
        } catch (final IOException ex) {
            ex.printStackTrace();
        } finally {
            if (s != null) {
                s.close();
            }
        }
        return result;
}

This gets first line as well.

Flatwise answered 3/2, 2015 at 21:19 Comment(0)
S
0

you can store it in array and then use whichever line you want.. this is the code snippet that i have used to read line from file and store it in a string array, hope this will be useful for you :)

public class user {
 public static void main(String x[]) throws IOException{
  BufferedReader b=new BufferedReader(new FileReader("<path to file>"));
  String[] user=new String[30];
  String line="";
  while ((line = b.readLine()) != null) {
   user[i]=line; 
   System.out.println(user[1]);
   i++;  
   }

 }
}
Subtile answered 7/1, 2016 at 7:9 Comment(0)
P
0

I think recursion would be the best approach here. Read a line store it in a String and if the string is not null print the line then call the function again. Now the buffer reader will read the next line and will continue until it has read all the lines.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class ReadFromFile {
    public static void main(String[] args){
        try {
            File file = new File("D:/temp.txt");
            FileReader fileReader = new FileReader(file);
            BufferedReader bufferedReader = new BufferedReader(fileReader);
            readFromFileAndPrint(bufferedReader);
        } catch(IOException ioException){}
    }
    private static void readFromFileAndPrint(BufferedReader bufferedReader) throws IOException {
        String line= bufferedReader.readLine();
        if (line!=null){
            System.out.println(line);
            readFromFileAndPrint(bufferedReader); // making a recursive call
        } else System.out.println("All lines have been read");
    }
}
Philippopolis answered 12/6, 2024 at 13:27 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.