RandomAccessFile.seek()无法在Linux

时间:2017-06-22 08:22:02

标签: java linux io randomaccessfile

我正在使用某种tail -f实现来拖尾文件以进行更改(非常像this)。为此,我使用RandomAccessFile,定期检查文件长度是否增加,如果是,请查找并读取新行(所有内容都发生在FileTailer的单独线程中)。

现在,一切都在Windows上按预期工作,但我在Linux上测试了我的程序并且它没有按预期工作。这是FileTailer类的run()方法。特别是它在linux上失败的部分是file.seek(filePointer)被调用的部分,然后是file.readLine(),后者令人惊讶地返回NULL(尽管如果我将内容添加到文件中,则filePointer会正确递增运行时)。

public void run() {
// The file pointer keeps track of where we are in the file
long filePointer = 0;

// Determine start point
if(startAtBeginning){
  filePointer = 0;
}
else {
  filePointer = logfile.length();
}

try {
  // Start tailing
  tailing = true;
  RandomAccessFile file = new RandomAccessFile(logfile, "r");
  while(tailing) {
      // Compare the length of the file to the file pointer
      long fileLength = logfile.length();
      System.out.println("filePointer = " + filePointer + " | fileLength = " + fileLength);
      if(fileLength < filePointer) {
        // Log file must have been rotated or deleted; 
        // reopen the file and reset the file pointer
        file = new RandomAccessFile(logfile, "r");
        filePointer = 0;
      }

      if(fileLength > filePointer) {
        // There is data to read
        file.seek(filePointer);
        String line = file.readLine();
        System.out.println("new line = " + line);
        while(line != null){
          if(!line.isEmpty())
            try {
                fireNewFileLine(line);
            } catch (ParseException e) {
                e.printStackTrace();
            }
          line = file.readLine();
        }
        filePointer = file.getFilePointer();
      }
      // Sleep for the specified interval
      sleep(sampleInterval);

  }

  // Close the file that we are tailing
  file.close();
}
catch(InterruptedException | IOException e){
  e.printStackTrace();
}
}

就像我说的,一切都在Windows上运行,但在Linux上,String变量“line”在应该填充新添加的行之后为NULL,因此fireNewLine在NULL上调用,一切都变为废话

有没有人知道为什么会在Linux系统上发生这种情况?

1 个答案:

答案 0 :(得分:0)

您不需要这一切,或RandomAccessFile。你总是在文件的末尾。所有你需要的是:

public void run() {

    try {
      // Start tailing
      tailing = true;
      BufferedReader reader = new BufferedReader(new FileReader(logfile));
      String line;
      while (tailing) {
          while ((line = reader.readLine() != null) {
              System.out.println("new line = " + line);
              if(!line.isEmpty()) {
                  try {
                      fireNewFileLine(line);
                  } catch (ParseException e) {
                      e.printStackTrace();
                  }
              }
          }
          // Sleep for the specified interval
          sleep(sampleInterval);
        }
        // Close the file that we are tailing
        reader.close();
    } catch(InterruptedException | IOException e) {
        e.printStackTrace();
    }
}

可能有一些重新打开文件的规定。

E&安培; OE