Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/webpack/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在java中轮询文件,将最新写入的文件内容获取为字符串_Java_File_Io_Polling - Fatal编程技术网

在java中轮询文件,将最新写入的文件内容获取为字符串

在java中轮询文件,将最新写入的文件内容获取为字符串,java,file,io,polling,Java,File,Io,Polling,我想创建一个java程序,它可以无限地轮询日志文件。每当日志文件中有一些条目时,我都会将最新的内容读入刚刚编写的文件中 有人能告诉我做这件事的有效方法吗?因为它应该全天候运行,所以不希望出现cpu峰值 我做了基础研究,发现了以下几点,但帮助不大: 一种非常简单有效的方法是使用WatchService。 下面是一个代码示例,它在创建、修改或删除文件时引发事件 import java.nio.file.Path; import java.nio.file.Paths; import java.nio

我想创建一个java程序,它可以无限地轮询日志文件。每当日志文件中有一些条目时,我都会将最新的内容读入刚刚编写的文件中

有人能告诉我做这件事的有效方法吗?因为它应该全天候运行,所以不希望出现cpu峰值

我做了基础研究,发现了以下几点,但帮助不大:
一种非常简单有效的方法是使用WatchService。 下面是一个代码示例,它在创建、修改或删除文件时引发事件

import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKind;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.List;

public static void main(String[] args) {

    //define a folder root
    Path myDir = Paths.get("D:/data");       

    try {
       WatchService watcher = myDir.getFileSystem().newWatchService();
       myDir.register(watcher, StandardWatchEventKind.ENTRY_CREATE, 
       StandardWatchEventKind.ENTRY_DELETE, StandardWatchEventKind.ENTRY_MODIFY);

       WatchKey watckKey = watcher.take();

       List<WatchEvent<?>> events = watckKey.pollEvents();
       for (WatchEvent event : events) {
            if (event.kind() == StandardWatchEventKind.ENTRY_CREATE) {
                System.out.println("Created: " + event.context().toString());
            }
            if (event.kind() == StandardWatchEventKind.ENTRY_DELETE) {
                System.out.println("Delete: " + event.context().toString());
            }
            if (event.kind() == StandardWatchEventKind.ENTRY_MODIFY) {
                System.out.println("Modify: " + event.context().toString());
            }
        }

    } catch (Exception e) {
        System.out.println("Error: " + e.toString());
    }
}
import java.nio.file.Path;
导入java.nio.file.path;
导入java.nio.file.StandardWatchEventKind;
导入java.nio.file.WatchEvent;
导入java.nio.file.WatchKey;
导入java.nio.file.WatchService;
导入java.util.List;
公共静态void main(字符串[]args){
//定义文件夹根目录
Path myDir=Path.get(“D:/data”);
试一试{
WatchService watcher=myDir.getFileSystem().newWatchService();
myDir.register(watcher、StandardWatchEventKind.ENTRY\u创建、,
StandardWatchEventKind.ENTRY\u删除,StandardWatchEventKind.ENTRY\u修改);
WatchKey WatchKey=watcher.take();

列表请阅读。这类问题不可接受,因为它太宽泛,也没有显示您的任何尝试(代码)。听起来您在寻找感谢@totolin的答案,但这并没有提取文件中所做的最新更改。我基本上是试图在附加后阅读文件中的最新内容。