使用RandomAccessFile监听日志文件,并实时一行行读取出来

发布时间 2024-01-08 14:42:01作者: 代码吴彦祖
public static void main(String[] args) {
        String filePath = "E:\\codes\\work\\product-parent\\logs\\alarm_log_info.log";
        try {
            RandomAccessFile randomAccessFile = new RandomAccessFile(filePath, "r");

            boolean keepWatching = true;

            while (keepWatching) {
                long filePointer = randomAccessFile.getFilePointer();
                String line = randomAccessFile.readLine();

                if (line == null) {
                    // 文件末尾,等待新数据
                    Thread.sleep(1000); // 可以根据实际情况调整等待时间
                } else {
                    // 处理新增的每一行日志数据
                    System.out.println(new String(line.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8));
                }

                // 检查文件是否有新数据
                //当前指针是否小于文件的总长度
                if (filePointer < randomAccessFile.length()) {
                    // 文件有新数据,继续读取
                } else {
                    // 文件没有新数据,等待一段时间再继续读取
                    Thread.sleep(1000); // 可以根据实际情况调整等待时间
                }

                // 添加退出循环的条件
//                if ("exit".equalsIgnoreCase("条件")) {
//                    keepWatching = false;
//                }
            }

            // 关闭资源
            randomAccessFile.close();

        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }