How do I read last n characters from a file?

In the following post you will learn how to read last n characters from a file. The JDK 7 introduces a new SeekableByteChannel interface which allows its implementation to change the position and the size of the byte channel. One of its implementation is the FileChannel class (java.nio.channels.FileChannel).

The FileChannel class make it possible to get hold the current position of where we are going to read from or write to a file. The code snippet below shows you how you can read the last 1000 characters from a log file.

The steps in the code snippet above are:

  1. Get the path to the log file.
  2. Create a ByteBuffer, a buffer where the read bytes to be transfered.
  3. Using the FileChannel.open() method we open  a file to be read and return a FileChannel object.
  4. The read() method of the FileChannel reads a sequence of bytes from the channel and transfer them to the given buffer starting and the position defined by channel.size() - 1000. This method returns the number of bytes read, possible zero, or -1 if the given position is greater than or equal to the file’s current size.
  5. Print out the buffered string.

How to monitor file or directory changes?

How to get the file name when using WatchService?