如何查看新内容的文件并检索该内容 [英] How to watch file for new content and retrieve that content

查看:191
本文介绍了如何查看新内容的文件并检索该内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 foo.txt 的文件。这个文件包含一些文本。我想实现以下功能:
$ b


  1. 我启动程序

  2. 写入文件例如添加一行: foo.txt中的新字符串

  3. 我只想得到这个文件的新内容。 >

你能澄清这个问题的最佳解决方案吗?另外我想解决相关的问题:如果我修改 foo.txt 我想看比较。



我在Java中找到的最接近的工具是 WatchService ,但是如果我明白这个工具只能检测文件系统上发生的事件类型(创建文件或删除或修改)。 >

解决方案

  final List< String> originalFileContents = new ArrayList< String>(); 
final String filePath =C:/Users/BackSlash/Desktop/asd.txt;

FileListener fileListener = new FileListener(){

@Override
public void fileDeleted(FileChangeEvent paramFileChangeEvent)
throws异常{
//使用这个来处理文件删除事件


$ b @Override
public void fileCreated(FileChangeEvent paramFileChangeEvent)
throws Exception {
//用它来处理文件创建事件


$ b @Override
public void fileChanged(FileChangeEvent paramFileChangeEvent)
抛出异常{
System。 out.println(File Changed);
//获取新内容
列表< String> newFileContents = new ArrayList< String> ();
getFileContents(filePath,newFileContents);
//获取两个文件之间的差异
Patch patch = DiffUtils.diff(originalFileContents,newFileContents);
//在列表中获得单个更改
列出< Delta> deltas = patch.getDeltas();
//打印更改
(Delta delta:deltas){
System.out.println(delta);
}
}
};

DefaultFileMonitor monitor = new DefaultFileMonitor(fileListener);
尝试{
FileObject fileObject = VFS.getManager()。resolveFile(filePath);
getFileContents(filePath,originalFileContents);
monitor.addFile(fileObject);
monitor.start();
} catch(InterruptedException ex){
ex.printStackTrace();
} catch(FileNotFoundException e){
//处理
e.printStackTrace();
catch(IOException e){
// handle
e.printStackTrace();



$ b $ getFileContents 是:

  void getFileContents(String path,List< String> contents)抛出FileNotFoundException,IOException {
contents.clear );
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(path),UTF-8));
String line = null; ((line = reader.readLine())!= null){
contents.add(line);
while




$ b $ p



  1. 我在 List< String> 中加载了原始文件内容。 li>我使用 Apache Commons VFS 来监听文件更改,使用 FileMonitor 。您可能会问, ?由于 WatchService 只能从Java 7开始使用,而 FileMonitor 至少可以使用Java 5(个人偏好,如果你更喜欢 WatchService 你可以使用它)。 note :Apache Commons VFS依赖于 Apache Commons Logging ,你必须添加到你的构建路径,以使其工作。

  2. 我创建了一个 FileListener ,然后我实现 fileChanged 方法。
  3. 该方法从文件中加载新内容,并使用 Patch.diff
  4. code>检索所有的差异,然后打印它们
  5. 我创建了一个 DefaultFileMonitor ,它基本上监听文件的变化,我添加了我的文件。

  6. 我启动了监视器。

监视器启动后,它将开始监听文件更改。


I have a file with name foo.txt. This file contains some text. I want to achieve following functionality:

  1. I launch program
  2. write something to the file (for example add one row: new string in foo.txt)
  3. I want to get ONLY NEW content of this file.

Can you clarify the best solution of this problem? Also I want resolve related issues: in case if I modify foo.txt I want to see diff.

The closest tool which I found in Java is WatchService but if I understood right this tool can only detect type of event happened on filesystem (create file or delete or modify).

解决方案

Java Diff Utils is designed for that purpose.

final List<String> originalFileContents = new ArrayList<String>();
final String filePath = "C:/Users/BackSlash/Desktop/asd.txt";

FileListener fileListener = new FileListener() {

    @Override
    public void fileDeleted(FileChangeEvent paramFileChangeEvent)
    throws Exception {
        // use this to handle file deletion event

    }

    @Override
    public void fileCreated(FileChangeEvent paramFileChangeEvent)
    throws Exception {
        // use this to handle file creation event

    }

    @Override
    public void fileChanged(FileChangeEvent paramFileChangeEvent)
    throws Exception {
        System.out.println("File Changed");
        //get new contents
        List<String> newFileContents = new ArrayList<String> ();
        getFileContents(filePath, newFileContents);
        //get the diff between the two files
        Patch patch = DiffUtils.diff(originalFileContents, newFileContents);
        //get single changes in a list
        List<Delta> deltas = patch.getDeltas();
        //print the changes
        for (Delta delta : deltas) {
            System.out.println(delta);
        }
    }
};

DefaultFileMonitor monitor = new DefaultFileMonitor(fileListener);
try {
    FileObject fileObject = VFS.getManager().resolveFile(filePath);
    getFileContents(filePath, originalFileContents);
    monitor.addFile(fileObject);
    monitor.start();
} catch (InterruptedException ex) {
    ex.printStackTrace();
} catch (FileNotFoundException e) {
    //handle
    e.printStackTrace();
} catch (IOException e) {
    //handle
    e.printStackTrace();
}

Where getFileContents is :

void getFileContents(String path, List<String> contents) throws FileNotFoundException, IOException {
    contents.clear();
    BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(path), "UTF-8"));
    String line = null;
    while ((line = reader.readLine()) != null) {
        contents.add(line);
    }
}

What I did:

  1. I loaded the original file contents in a List<String>.
  2. I used Apache Commons VFS to listen for file changes, using FileMonitor. You may ask, why? Because WatchService is only available starting from Java 7, while FileMonitor works with at least Java 5 (personal preference, if you prefer WatchService you can use it). note: Apache Commons VFS depends on Apache Commons Logging, you'll have to add both to your build path in order to make it work.
  3. I created a FileListener, then I implemented the fileChanged method.
  4. That method load new contents form the file, and uses Patch.diff to retrieve all differences, then prints them
  5. I created a DefaultFileMonitor, which basically listens for changes to a file, and I added my file to it.
  6. I started the monitor.

After the monitor is started, it will begin listening for file changes.

这篇关于如何查看新内容的文件并检索该内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆