私はtail -f実装を使ってファイルを変更します(ほとんど同じようにthisのように)。私はRandomAccessFileを使用しています。ファイルの長さが増えたかどうか定期的にチェックし、そうであれば新しい行を探して読み込みます(FileTailerの別のスレッドですべてが発生します)。LinuxでRandomAccessFile.seek()が動作しません
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();
}
}
私はそれが新しく追加行で満たされている必要がありますので、fireNewLineがNULLに呼び出された後、それはWindows上で必要としてすべてが働いているが、Linux上の文字列変数「ライン」はNULLで、言ったようにとすべてが駄目になる。
Linuxシステムでこれが起こる理由を知っている人はいますか?
'(求めていることをここに証拠はありません)'問題ですが、 ''まったく)(求める呼んでいる理由を私は知りません。あなたはする必要はありません。常にファイルの最後に配置する必要があります。あなた自身の 'readLine()'呼び出しを除いてファイル内のあなたの位置を変更するものはありません。 – EJP
実際、あなたは 'RandomAccessFile'をすべて必要としません。 'BufferedReader'を使い、' readLine() 'がnullを返す間だけスリープします。 – EJP