3

I am trying to use a simple program to read from a log file. The code used is as follows:

RandomAccessFile in = new RandomAccessFile("/home/hduser/Documents/Sample.txt", "r");
String line;
while(true) {
if((line = in.readLine()) != null) {
System.out.println(line);
} else {
Thread.sleep(2000); 

The code works well for new lines being added to the log file but it does not replicate the rollover process. i.e. when the content of the log file is cleared I expect the java console to continue reading text from the first line newly written to the log. Could that be possible? What changes need to be made to the existing code to achieve that?

4

3 回答 3

2

在我的工作中,我必须处理可以翻转而不会丢失任何数据的日志的处理。我所做的是存储一个包含以下内容的小备忘录文件:

  • 日志前 1024 个字节(或更少)的哈希值(我使用 SHA-1 或其他东西,因为它很简单)
  • 用于生成哈希的字节数
  • 当前文件位置

我在处理完所有行或某个最大行数后关闭日志文件,然后更新备忘录文件。我睡了一会儿,然后再次打开日志文件。这使我可以检查是否发生了翻转。在以下情况下检测到翻转:

  1. 当前文件小于上一个文件位置
  2. 哈希不一样

就我而言,我可以使用散列来找到正确的日志文件,并向后工作以获取最新信息。一旦我知道我已经在正确的文件中找到了我离开的地方,我就可以继续阅读和记住我的位置。我不知道这是否与您想做的事情有关,但也许这会给您一些想法。

如果您没有任何持久性要求,您可能不需要存储任何备忘录文件。如果您的“翻转”只是清除日志并且没有将其移开,您可能不需要记住任何文件哈希。

于 2013-05-15T06:26:32.477 回答
1

I am sorry... My Bad.. I don't want it to go blank.. I just want the next new line written to the log to be read.

由于您需要在文件被清除时从头开始读取,因此您需要监控文件长度并在文件长度减少时重置光标指针。您可以使用方法重置光标seek(..)

请参阅下面的代码 -

RandomAccessFile in = new RandomAccessFile("/home/hduser/Documents/Sample.txt", "r");
String line;
long length = 0;//used to check the file length
while (true) {
    if(in.length()<length){//new condition to reset position if file length is reduced 
        in.seek(0);
    }
    if ((line = in.readLine()) != null) {
        System.out.println(line);
        length = in.length();
    } else {
        Thread.sleep(2000);
    }
}
于 2013-05-15T06:56:24.097 回答
0

它不会复制翻转过程。即当日志文件的内容被清除时,我希望java控制台继续从新写入日志的第一行读取文本。这可能吗?

也在为此苦苦挣扎。向@paddy +1 了解哈希的想法。

另一种解决方案(取决于您的操作系统)是使用文件的 inode,尽管这可能仅适用于 unix:

Long inode = (Long)Files.getAttribute(logFile.toPath(), "unix:ino");

这将返回与 log-file 关联的底层文件系统的 inode。如果 inode 发生更改,则该文件是一个全新的文件。这假设当日志翻转时,它被移到一边,并且相同的文件没有被覆盖。

为了完成这项工作,您将记录您正在阅读的文件的 inode,然后如果您在一段时间内没有获得任何新数据,请检查 inode 是否已更改。

于 2021-04-08T22:49:51.523 回答