Я пытаюсь реализовать простую команду tail -f linux в java. Вот мой код.
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);
}
Не знаю почему, но теперь и под линуксом работает нормально. Спасибо за ваши усилия, ребята