package fr.expdev.fromendreader; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; public class FromEndReader { private final File file; private final RandomAccessFile raf; private int max; private long position; public FromEndReader(final String file, final int max) throws IOException { super(); this.max = max; this.file = new File(file); raf = new RandomAccessFile(this.file, "r"); position = raf.length(); } public String readLine() throws IOException { StringBuilder line = new StringBuilder(); byte code = 0; while (--position >= 0 & max != 0) { raf.seek(position); code = raf.readByte(); if (code == 13 || code == 10) { raf.seek(position - 1); int nextCode = raf.readByte(); max--; if ((code == 13 && nextCode == 10) || (code == 10 && nextCode == 13)) { position--; } break; } line.insert(0, (char) code); max--; } if (line.length() == 0) { return null; } else { return line.toString(); } } public Byte readByte() throws IOException { Byte theByte = null; if (position > 0 && max != 0) { raf.seek(position - 1); theByte = raf.readByte(); position--; max--; } return theByte; } public void close() throws IOException { raf.close(); } }