Efficient way to handle file pointers in Java? (Using BufferedReader with a file pointer)

I have a log file that is updated every second. I need to periodically read the log file, and as soon as I read, I need to save the position of the file pointer at the end of the last line read and in the next periodic reading I have to start from this point.

I am currently using a random access file in Java and using a method getFilePointer()to get the offset value and the method seek()to the offset position.

However, I have read in most articles and even recommendations of Java doc to use BufferredReaderfor effective reading of a file. How can I achieve this (getting the file and going to the last line) with BufferedReader, or is there another effective way to achieve this?

+5
source share
3 answers

A few ways that should work:

  • open the file with FileInputStream, skip () the appropriate number of bytes, then wrap the BufferedReader around the stream (via InputStreamReader);
  • ( FileInputStream RandomAccessFile), getChannel() stream/RandomAccessFile, FileChannel, () , Channels.newInputStream(), , InputStreamReader → BufferedReader.

, , , , .

RandomAccessFile , readLine() . RAF , , RAF , readLine()

+4

Neil Coffey , . ( ) BufferedReader FileInputStream FileChannel InputStreamReader.

  • 1) . , BR FileInputStream/FileChannel ( InputStreamReader) readLine. , , , BF readLine , ( ).

  • 2) readLine, / , , / , , .

, ( readLine, , )

​​ BufferedReader .

/** Read data from offset to length bytes in RandomAccessFile using BufferedReader
 * @param offset
 * @param length
 * @param accessFile
 * @throws IOException
 */
    public static void readBufferedLines(long offset, long length, RandomAccessFile accessFile) throws IOException{
    if(accessFile == null) return;
    int bufferSize = BYTE_BUFFER_SIZE;// constant say 4096

    if(offset < length && offset >= 0){ 
        int index = 1;
        long curPosition = offset;
        /*
         * iterate (length-from)/BYTE_BUFFER_SIZE times to read into buffer no matter where new line occurs
         */
        while((curPosition + (index * BYTE_BUFFER_SIZE)) <  length){        

            accessFile.seek(offset); // seek to last parsed data rather than last data read in to buffer

            byte[] buf = new byte[bufferSize];
            int read = accessFile.read(buf, 0, bufferSize);
            index++;// Increment whether or not read successful

            if(read > 0){

                int lastnewLine = getLastLine(read,buf);

                if(lastnewLine <= 0){ // no new line found in the buffer reset buffer size and continue
                    bufferSize = bufferSize+read;
                    continue;

                }
                else{
                    bufferSize = BYTE_BUFFER_SIZE;
                }

                readLine(buf, 0, lastnewLine); // read the lines from buffer and parse the line

                offset = offset+lastnewLine; // update the last data read

            }

        }



        // Read last chunk. The last chunk size in worst case is the total file when no newline occurs 
        if(offset < length){

            accessFile.seek(offset); 
            byte[] buf = new byte[(int) (length-offset)];
            int read = accessFile.read(buf, 0, buf.length);

            if(read > 0){

                readLine(buf, 0, read);

                offset = offset+read; // update the last data read


            }
        }


    }

}

private static void readLine(byte[] buf, int from , int lastnewLine) throws IOException{

    String readLine = "";
    BufferedReader reader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(buf,from,lastnewLine) ));
    while( (readLine =  reader.readLine()) != null){
        //do something with readLine
        System.out.println(readLine);
    }
    reader.close();
}


private static int getLastLine(int read, byte[] buf) {
    if(buf == null ) return -1;
    if(read > buf.length) read = buf.length;
    while( read > 0 && !(buf[read-1] == '\n' || buf[read-1] == '\r')) read--;       
    return read;
}   
 public static void main(String[] args) throws IOException {
    RandomAccessFile accessFile = new RandomAccessFile("C:/sri/test.log",    "r");
    readBufferedLines(0, accessFile.length(), accessFile);
    accessFile.close();

}
+1

, , BufferedStream , , getBytes(). , , BufferedReader seek() .

public class FileCounterIterator {

    public Long position() {
        return _position;
    }

    public Long fileSize() {
        return _fileSize;
    }

    public FileCounterIterator newlineLength(Long newNewlineLength) {
        this._newlineLength = newNewlineLength;
        return this;
    }

    private Long _fileSize = 0L;
    private Long _position = 0L;
    private Long _newlineLength = 1L;
    private RandomAccessFile fp;
    private BufferedReader itr;

    public FileCounterIterator(String filename) throws IOException {
        fp = new RandomAccessFile(filename, "r");
        _fileSize = fp.length();
        this.seek(0L);
    }

    public FileCounterIterator seek(Long newPosition) throws IOException {
        this.fp.seek(newPosition);
        this._position = newPosition;
        itr = new BufferedReader(new InputStreamReader(new FileInputStream(fp.getFD())));
        return this;
    }

    public Boolean hasNext() throws IOException {
        return this._position < this._fileSize;
    }

    public String readLine() throws IOException {
        String nextLine = itr.readLine();
        this._position += nextLine.getBytes().length + _newlineLength;
        return nextLine;
    }
}
0
source

All Articles