7

I have a crawler program which logs some files. Sometimes on the server, some error happens and the crawler creates massive log files which are somehow impossible to parse. For that reason, I wanted to create a simple program which reads about 1000 characters at the end of the log file and shows the messages to me (even if the crawler is still writing to that file). This will help me solve the problem without closing the crawler.

Hugo Dozois
  • 8,147
  • 12
  • 54
  • 58
Alireza Noori
  • 14,961
  • 30
  • 95
  • 179

3 Answers3

15

Using a RandomAccessFile to seek, then read your bytes out.

File file = new File("DemoRandomAccessFile.out");
RandomAccessFile raf = new RandomAccessFile(file, "r");

// Seek to the end of file
raf.seek(file.length() - n);
// Read it out.
raf.read(yourbyteArray, 0, n);
StarPinkER
  • 14,081
  • 7
  • 55
  • 81
  • 1
    This is more relevant to my question, so I choose this as the answer. But I'm going with [Tail for Win32](http://tailforwin32.sourceforge.net/) ;) – Alireza Noori Mar 09 '13 at 23:40
  • shouldn't use "rw" only "r", because the write mode in most windows environment will put a lock to file and the logger will not able to write the logs, that's why I told to open in read mode –  Mar 12 '13 at 08:54
  • If it's important to read all of the bytes, remember that the read method is not guaranteed to read more than one byte. Consider using `raf.readFully(yourbyteArray)` to make sure that you're reading all of the bytes that make up the length of the buffer that is being read into. – Guus Feb 25 '22 at 15:24
3

There is a handy command line tool for this already on your computer. tail -c 1000 would do what you are asking for. tail -n 10 printing out the last 10 lines may be even more useful.

s.bandara
  • 5,636
  • 1
  • 21
  • 36
2

Check the file length, lets say 1Mb

Open for read with RandomAccessFile

Seek to position to 1024*1024-1000

read 1000 bytes

upvote :)

  • Since the [Tail for Win32](http://tailforwin32.sourceforge.net/) does what I want, I don't need this, but this is exactly the way to go, hence the upvode ;) – Alireza Noori Mar 09 '13 at 23:38