Java : Read last n lines of a HUGE file

后端 未结 11 1749
温柔的废话
温柔的废话 2020-11-27 04:59

I want to read the last n lines of a very big file without reading the whole file into any buffer/memory area using Java.

I looked around the JDK APIs and Apache Com

11条回答
  •  迷失自我
    2020-11-27 05:18

    I had similar problem, but I don't understood to another solutions.

    I used this. I hope thats simple code.

    // String filePathName = (direction and file name).
    File f = new File(filePathName);
    long fileLength = f.length(); // Take size of file [bites].
    long fileLength_toRead = 0;
    if (fileLength > 2000) {
        // My file content is a table, I know one row has about e.g. 100 bites / characters. 
        // I used 1000 bites before file end to point where start read.
        // If you don't know line length, use @paxdiablo advice.
        fileLength_toRead = fileLength - 1000;
    }
    try (RandomAccessFile raf = new RandomAccessFile(filePathName, "r")) { // This row manage open and close file.
        raf.seek(fileLength_toRead); // File will begin read at this bite. 
        String rowInFile = raf.readLine(); // First readed line usualy is not whole, I needn't it.
        rowInFile = raf.readLine();
        while (rowInFile != null) {
            // Here I can readed lines (rowInFile) add to String[] array or ArriyList.
            // Later I can work with rows from array - last row is sometimes empty, etc.
            rowInFile = raf.readLine();
        }
    }
    catch (IOException e) {
        //
    }
    

提交回复
热议问题