我有一个名为foo.txt
。该文件包含一些文本。我想实现以下功能:
- 我启动程序
- 向文件写入一些内容(例如添加一行:
new string in foo.txt
)
- 我只想获取该文件的新内容。
您能阐明这个问题的最佳解决方案吗?我还想解决相关问题:如果我修改foo.txt
我想看看差异。
我在 Java 中找到的最接近的工具是WatchService
但如果我理解正确的话,这个工具只能检测文件系统上发生的事件类型(创建文件或删除或修改)。
Java 差异实用程序就是为此目的而设计的。
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);
}
}
我做了什么:
- 我将原始文件内容加载到
List<String>
.
- I used Apache 共享 VFS监听文件更改,使用
FileMonitor
。你可能会问,why?因为WatchService
仅从 Java 7 开始可用,而FileMonitor
至少适用于 Java 5(个人喜好,如果您愿意的话)WatchService
你可以使用它)。note:Apache Commons VFS 依赖Apache 公共日志记录,您必须将两者添加到构建路径中才能使其正常工作。
- 我创建了一个
FileListener
,然后我实现了fileChanged
method.
- 该方法从文件中加载新内容,并使用
Patch.diff
检索所有差异,然后打印它们
- 我创建了一个
DefaultFileMonitor
,它基本上监听文件的更改,然后我将我的文件添加到其中。
- 我启动了监视器。
监视器启动后,它将开始监听文件更改。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)