[java] Using BufferedReader to read Text File

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.

Thanks in advance!

This question is related to java file text

The answer is


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);
    }

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();

}

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();
}

Try:

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

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++;  
   }

 }
}

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);
  }

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) {

}

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.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to file

Gradle - Move a folder from ABC to XYZ Difference between opening a file in binary vs text Angular: How to download a file from HttpClient? Python error message io.UnsupportedOperation: not readable java.io.FileNotFoundException: class path resource cannot be opened because it does not exist Writing JSON object to a JSON file with fs.writeFileSync How to read/write files in .Net Core? How to write to a CSV line by line? Writing a dictionary to a text file? What are the pros and cons of parquet format compared to other formats?

Examples related to text

Difference between opening a file in binary vs text How do I center text vertically and horizontally in Flutter? How to `wget` a list of URLs in a text file? Convert txt to csv python script Reading local text file into a JavaScript array Python: How to increase/reduce the fontsize of x and y tick labels? How can I insert a line break into a <Text> component in React Native? How to split large text file in windows? Copy text from nano editor to shell Atom menu is missing. How do I re-enable