Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read last n bytes of file using Java

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.

like image 359
Alireza Noori Avatar asked Mar 09 '13 23:03

Alireza Noori


2 Answers

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);
like image 99
StarPinkER Avatar answered Sep 28 '22 13:09

StarPinkER


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.

like image 35
s.bandara Avatar answered Sep 28 '22 11:09

s.bandara