i use LineNumberReader to read text file , when call setLineNumber and getLinenumber it print == 0 But when call readLine again ์Nit thing happen how can i fix it
Here is my code
BufferedWriter writer = new BufferedWriter(new FileWriter("text.txt"));
writer.write("This is a line1\n" +
"This is a line2\n" +
"This is a line3");
writer.newLine();
writer.close();
File myFile = new File("text.txt");
FileReader fileReader = new FileReader(myFile);
LineNumberReader reader = new LineNumberReader(fileReader);
// Read from the FileReader.
String lineRead = "";
while ((lineRead = reader.readLine()) != null) {
System.out.println(lineRead);
}
// Determine the number of lines that were read.
System.out.println("Total lines read: " +
reader.getLineNumber());
// Reset the number of lines read.
reader.setLineNumber(0);
System.out.println("Total lines read after reset: " +
reader.getLineNumber());
String lineRead2 = "";
while ((lineRead2 = reader.readLine()) != null) {
System.out.println(lineRead2);
}
System.out.println("End");
// Close the LineNumberReader and FileReader.
fileReader.close();
reader.close();
Thank
You are just setting the
LineNumberReader‘s line number counter, not the position in the underlying stream. See the documentation for Java’s LineNumberReader class.You have already processed your stream, and thus a subsequent call to
readLine()returns null.If you want to reread the stream, you’re going to have to call
fileReader.reset(), orreader.reset(), which will result in yourLineNumberReadercalling the reset for yourFileReader.