简体   繁体   English

如何使用Java检测Windows文本文件中是否有最近的更改

[英]How to detect if there is recent change in windows text file using Java

Hi guys I am writing a small application in java where it reads a text file and parses the contents. 大家好我在java中编写一个小应用程序,它读取文本文件并解析内容。 My problem is my program will keep on reading the file because its inside a loop. 我的问题是我的程序将继续读取文件,因为它在一个循环内。 My solution was to implement similar to what I usually do in linux like (see below) 我的解决方案是实现类似于我在linux中通常做的事情(见下文)

ls -l -ctime 
or 
ls -l -atime

where it detects when the files was last accessed or written If you solution can be done in java or some windows command can you please let me know. 它检测文件上次访问或写入的时间如果您可以在java中执行解决方案或某些Windows命令,请告诉我。 Thanks 谢谢

Update: 更新:

Thanks very much for helping 非常感谢您的帮助

Westons Solution 威斯顿解决方案

public static long checkLastFileModification() throws InterruptedException{

    File file = new File(fileName);
    long lastProcessed = -1;

    while (true){
        long lastModified = file.lastModified();

        if (lastProcessed != lastModified){
            lastProcessed = lastModified;
            System.out.println("Last accessed : " + lastModified);
            //read the file in reverse order

        }
        else{
            System.out.println("No file access.... sleeping for 5 secs ");
            Thread.sleep(5000);
        }
    }

}

If you want to show it every single loop, then make a batch file named "loop.bat" in the same folder the project/program is. 如果要在每个循环中显示它,请在项目/程序所在的同一文件夹中创建名为“loop.bat”的批处理文件。 loop.bat must have the following contents: loop.bat必须具有以下内容:

@echo off
goto loop
:loop
cls
title Seeing file's contents.
type filename.txt
goto loop

And rename "filename.txt" with the text file you want to see. 并使用您要查看的文本文件重命名“filename.txt”。 Now make a java code to show text that it has a batch file running seeing the contents of the file. 现在创建一个java代码来显示它有一个运行批处理文件的文本,看看文件的内容。 Or if you can, print the text on the batch file to the java. 或者,如果可以,将批处理文件上的文本打印到java。

filename.txt, loop.bat and your java program must be in the same folder. filename.txt,loop.bat和你的java程序必须在同一个文件夹中。

You can inspect the last modified time of the file: 您可以检查文件的上次修改时间

new File(fileName).lastModified()

In your loop you can see if it is different: 在循环中,您可以看到它是否不同:

long lastProcessed = -1;
File file = new File(fileName);
while(true) {
   long lastModified = file.lastModified();
   if (lastProcessed != lastModified) {
      lastProcessed = lastModified;
      process(file);
   }
   else {
     //some delay or sleep, else you're thrashing the thread and file
   }
}

I would suggest to use WatchService API.See in below exmple. 我建议使用WatchService API。参见下面的例子。

http://java.dzone.com/news/how-watch-file-system-changes http://java.dzone.com/news/how-watch-file-system-changes

See API :- WatchService 请参阅API: - WatchService

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM