1
I need to recover a file always the last line written. I know one way to do this would be:
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
public class LineReader {
public static void main(String[] args) throws Exception {
LineNumberReader lineCounter = new LineNumberReader(new InputStreamReader(new FileInputStream("C:\\MyFile.txt")));
String nextLine = null;
try {
while ((nextLine = lineCounter.readLine()) != null) {
if (nextLine == null)
break;
System.out.println(nextLine);
}
System.out.println("Total number of line in this file " + lineCounter.getLineNumber());
} catch (Exception done) {
done.printStackTrace();
}
}
}
But is there any method ready in java to get this line without having to go through all the lines of the file? Even more than I’ll ever know how many lines he already has.
And if the file is 20GB?
– Tom Melo
@Tommelo In this case you will probably have one
OutOfMemoryError
. If not, it should work, but it will clutter up the memory and make a lot of work for the garbage collector. However, if you are having to read 20 Gb text files sequentially, your approach to the problem is clearly not appropriate.– Victor Stafusa
So in this case, if I have to read the last line of a 20GB file this approach of Files.readAllLines is not appropriate, correct?
– Tom Melo
@Tommelo: https://answall.com/a/244450/132
– Victor Stafusa
Exactly! It was my question, a solution that meets any scenario. I think it would be nice to edit and put the solution with Randomaccessfile.
– Tom Melo