我试图在 java 中实现简单的 tail -f linux 命令。这是我的代码。
try
{
// position within the file
File file = new File("/home/curuk/monitored/log.txt");
RandomAccessFile raFile = new RandomAccessFile(file, "r");
long last = file.lastModified(); // The last time the file was checked for changes
long position = file.length();
while (true)
{
if (file.lastModified() > last)
{
last = file.lastModified();
readFromFile(raFile, (int) position, (int) (file.length() - position));
position = file.length();
}
Thread.sleep(1000);
}
}
catch (IOException e)
{
e.printStackTrace();
}
private byte[] readFromFile(RandomAccessFile file, int position, int size) throws IOException
{
file.seek(position);
byte[] bytes = new byte[size];
System.err.println(file.read(bytes, 0, size));
String s = new String(bytes);
System.err.println(s);
return bytes;
}
问题是在 linux 操作系统下,file.read(bytes, 0, size)
总是返回 -1,而在 Windows 下,相同的代码片段工作得很好(总是打印新行)。
编辑:
我通过raFile = new RandomAccessFile(file, "r");
在每次迭代中添加来解决问题。
while (true)
{
raFile = new RandomAccessFile(file, "r");
if (file.lastModified() > last)
{
last = file.lastModified();
readFromFile(raFile, (int) position, (int) (file.length() - position));
position = file.length();
}
Thread.sleep(1000);
}
不知道为什么,但现在在 Linux 下也可以正常工作。谢谢你们的努力