DaNyAl mAlIk
DaNyAl mAlIk

Reputation: 11

How to read a single line from file in java

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 function and converting it into string will skip a lot of data? what should be the problem? Here is my code

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

Upvotes: 1

Views: 8367

Answers (3)

Rahul
Rahul

Reputation: 45040

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

Upvotes: 1

Vimal Bera
Vimal Bera

Reputation: 10497

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.

Upvotes: 0

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35547

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

Upvotes: 2

Related Questions