Get the contents of the last line of a file in Java

1

I need to retrieve from 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 java-ready method to get this line without having to go through all the lines in the file? Even more that I will never know how many lines he already has.

    
asked by anonymous 08.10.2017 / 19:12

4 answers

4

Try using the Files.readAllLines(Path) :

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;

/**
 * @author Victor Stafusa
 */
public class LerArquivo {

    public static void main(String[] args) throws IOException {
        List<String> linhas = Files.readAllLines(new File("C:\MyFile.txt").toPath());
        System.out.println("Número de linhas: " + linhas.size());
        System.out.println("Última linha: " + linhas.get(linhas.size() - 1));
    }
}
    
08.10.2017 / 19:25
2

Since you do not know the number of lines or file size: RandomAccessFile .

You can do your own implementation or use the Apache Commons IO implementation: link

ReversedLinesFileReader reader = new ReversedLinesFileReader(new File("seu-arquivo.txt"), StandardCharsets.UTF_8);
System.out.println(reader.readLine());
reader.close();
    
08.10.2017 / 20:33
0

In the Java 7 version the Files.readAllLines (Path p, Charset cs) method requires the final attribute to specify the character that will serve as a reference for the line break. I suggest you add:

    List<String> lines = Files.readAllLines(
          new File("C:\MyFile.txt").toPath(),     
          Charset.defaultCharset()
    );
    
08.10.2017 / 19:51
0

For files that are very large (a few gigabytes), most approaches would read it sequentially, which would be too slow and might give OutOfMemoryError if the program stores all of it in memory.

To solve this problem, follow an approach that reads the file backwards:

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * @author Victor Stafusa
 */
public class LerArquivoDeTrasParaFrente {
    public static void main(String[] args) throws IOException {
        File f = new File("C:\MyFile.txt");
        try (RandomAccessFile raf = new RandomAccessFile(f, "r")) {
            byte b = 0;
            long t = raf.length();
            for (long n = 0; t - n >= 0 && b != '\r' && b != '\n'; n++) {
                raf.seek(t - n);
                b = (byte) raf.read();
            }
            System.out.println("A última linha é: " + raf.readLine());
        }
    }
}
    
08.10.2017 / 20:49