简体   繁体   English

使用Java读取文件的最后n个字节

[英]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). 出于这个原因,我想创建一个简单的程序,它在日志文件的末尾读取大约1000个字符并向我显示消息(即使爬虫仍在写入该文件)。 This will help me solve the problem without closing the crawler. 这将帮助我在不关闭爬虫的情况下解决问题。

Using a RandomAccessFile to seek , then read your bytes out. 使用RandomAccessFile进行搜索 ,然后读出你的字节。

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);

There is a handy command line tool for this already on your computer. 您的计算机上已有一个方便的命令行工具。 tail -c 1000 would do what you are asking for. tail -c 1000会做你想要的。 tail -n 10 printing out the last 10 lines may be even more useful. tail -n 10打印掉最后10行可能更有用。

Check the file length, lets say 1Mb 检查文件长度,比如说1Mb

Open for read with RandomAccessFile 使用RandomAccessFile打开以供阅读

Seek to position to 1024*1024-1000 寻求定位到1024 * 1024-1000

read 1000 bytes 读取1000个字节

upvote :) upvote :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM