Using BufferedReader to read Text File

前端 未结 9 1354
你的背包
你的背包 2020-11-29 04:29

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[         


        
相关标签:
9条回答
  • 2020-11-29 04:59

    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.

    0 讨论(0)
  • 2020-11-29 05:04

    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();
    }
    
    0 讨论(0)
  • 2020-11-29 05:05

    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++;  
       }
    
     }
    }
    
    0 讨论(0)
  • 2020-11-29 05:07

    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();
    
    }
    
    0 讨论(0)
  • 2020-11-29 05:10

    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) {
    
    }
    
    0 讨论(0)
  • 2020-11-29 05:14

    Try:

    String text= br.readLine();
    while (text != null) 
    {
      System.out.println(text);
      text=br.readLine();
    }
    in.close();
    
    0 讨论(0)
提交回复
热议问题