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.
Asked
Active
Viewed 6,778 times
7
-
And the question is? What have you tried? – JB Nizet Mar 09 '13 at 23:19
-
4`tail /your/file` if you're on Linux/Unix. – Lukas Knuth Mar 09 '13 at 23:22
-
@LukasKnuth: +1. Should have mentioned -f for +2... ;-) – Axel Mar 09 '13 at 23:26
-
@Axel `-f` would have also followed. He said that the file might be written to while he wants to fetch the last few lines. – Lukas Knuth Mar 09 '13 at 23:29
-
Yes, I think that's quite handy. Normally I do something like `tail -f /your/file | grep error_of_interest` – Axel Mar 09 '13 at 23:32
-
BTW there was a windows tag added to the question, so no tail in default install... – Axel Mar 09 '13 at 23:33
3 Answers
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
-
1This 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
-
-
Awesome. Thanks. [Tail for Win32](http://tailforwin32.sourceforge.net/) did it for me. – Alireza Noori Mar 09 '13 at 23:39
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