Java: 如何一遍又一遍地轮询一个小文件,看看它是否发生了变化? (观看无法正常工作)

Java: how to poll a small file over and over to see if it changed? (watching can't work)

在 Java 8+ 到 poll/read 一个小的普通 ASCII 文件来检查它是否改变的开销最小的方法是什么?

我有一个设备可以创建一个伪造的文件系统 (ev3dev),它提供带有状态更新的小型只读文件。 (例如,乐高电机在 position 文件中的位置具有单个 Int,或电机在 status 文件中具有单个字符串的状态,两者均作为纯 ASCII 文件提供)

无效的事情

  1. Java's Watcher service 不起作用,我认为是因为从未通知 OS 文件已更改。 (修改时间保持不变,文件大小不变。)我试过了——它永远不会触发。好吧!
  2. 设置 mark()reset() 来一遍又一遍地读取文件而不创建新的 Reader 似乎在 BufferedReader 上不起作用,是有办法让它发挥作用吗?

我想我必须投票:快速地一遍又一遍地阅读文件(一遍又一遍!)

您可以将 RandomAccessFile class 用于您的代码。

我的代码:

import java.io.*; //Importing RandomAccessFile Class
import java.util.*; // Thread.sleep(milliseconds)
public class Main {
    public static void main(String[] args) throws Exception {
        Scanner scan = new Scanner(System.in);
        /*Just To add functionality I have also specified the time at which the file is modified*/
        System.out.println("Input File Path : ");
        String file_path = scan.nextLine();
        RandomAccessFile f = new RandomAccessFile(file_path,"r");
        int character;
        String Intitalval="";
        while ((character = f.read()) != -1) {
            Intitalval+=(char)character;
        }
        f.seek(0);
        boolean nochange = true;
        while (nochange) {
            String ToCompare="";
            while ((character = f.read()) != -1) {
                ToCompare+=(char)character;
            }

            if (!ToCompare.equals(Intitalval)) {
                nochange = false;
                System.out.println("The file has been modified at " + java.time.LocalTime.now());
            }
            Thread.sleep(1);
            f.seek(0);
        }
        f.close();
    }
}

正如你所说,你想要延迟 1 毫秒,我使用了 java Thread.sleep(int milliseconds) 方法。

程序还会显示文件被修改的时间(不准确(+- 毫秒))。

输出: