How to read a single line from file in java

前端 未结 3 1076
长情又很酷
长情又很酷 2020-12-22 08:41

How can i read single line from a text file in java. and what is the criteria of knowing that line is completed.

secondly

i read file and then for Read Line

相关标签:
3条回答
  • 2020-12-22 09:10

    You are reading an extra line because the first readLine() as the while condition reads a line but it is used at all. The second readLine() inside the while loop read the second line which you're assigning to data and printing.

    Therefore you need to assign the line read in the while condition to data and print it, as that is the first line.

    while((data = infile.readLine()) != null) { // reads the first line
        // data = infile.readLine(); // Not needed, as it reads the second line
        System.out.println(data); // print the first line
    }
    

    Also, since you just need to read the first line, you don't need the while at all. A simple if would do.

    if((data = infile.readLine()) != null) { // reads the first line
        System.out.println(data); // print the first line
    }
    

    With the BufferedReader and the code you posted in the comments, your main should now look like this.

    public static void main(String[] args) {
        try {
            FileInputStream fstream = new FileInputStream(args[0]);
            BufferedReader infile = new BufferedReader(new InputStreamReader(
                    fstream));
            String data = new String();
            while ((data = infile.readLine()) != null) { // use if for reading just 1 line
                System.out.println(data);
            }
        } catch (IOException e) {
            // Error
        }
    }
    
    0 讨论(0)
  • 2020-12-22 09:12

    Change your code as follows

      while((data = infile.readLine()) != null) {  // read and store only line    
      System.out.println(data);
      }
    

    In your current code

       while(infile.readLine() != null) { // here you are reading one and only line
       data = infile.readLine(); // there is no more line to read
        System.out.println(data);
       }
    
    0 讨论(0)
  • 2020-12-22 09:22

    First thing : readLine() returns String value only so it is not converting to String.

    Second thing : In your while loop, you read firstline and check whether the content of first line is null or not. But when data = infile.readLine(); executes, it will fetch second line from file and print it to Console.

    Change your while loop to this :

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

    If you use toString() method, it will throw NPE when it will try to use toString method with null content read from infile.

    0 讨论(0)
提交回复
热议问题