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