Java:在不锁定文件的情况下打开和读取文件 [英] Java: opening and reading from a file without locking it

查看:542
本文介绍了Java:在不锁定文件的情况下打开和读取文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要能够用Java模仿'tail -f'。我正在尝试读取一个日志文件,因为它是由另一个进程写的,但是当我打开文件来读取它时,它会锁定文件而另一个进程无法再写入它。任何帮助将不胜感激!

I need to be able to mimic 'tail -f' with Java. I'm trying to read a log file as it's being written by another process, but when I open the file to read it, it locks the file and the other process can't write to it anymore. Any help would be greatly appreciated!

这是我目前使用的代码:

Here is the code that I'm using currently:

public void read(){
    Scanner fp = null;
    try{
        fp = new Scanner(new FileReader(this.filename));
        fp.useDelimiter("\n");
    }catch(java.io.FileNotFoundException e){
        System.out.println("java.io.FileNotFoundException e");
    }
    while(true){
        if(fp.hasNext()){
            this.parse(fp.next());
        }           
    }       
}


推荐答案

由于文件截断和(中间)删除等特殊情况,重建尾部很棘手。要在不锁定的情况下打开文件,请使用新的Java文件API使用 StandardOpenOption.READ ,如下所示:

Rebuilding tail is tricky due to some special cases like file truncation and (intermediate) deletion. To open the file without locking use StandardOpenOption.READ with the new Java file API like so:

try (InputStream is = Files.newInputStream(path, StandardOpenOption.READ)) {
    InputStreamReader reader = new InputStreamReader(is, fileEncoding);
    BufferedReader lineReader = new BufferedReader(reader);
    // Process all lines.
    String line;
    while ((line = lineReader.readLine()) != null) {
        // Line content content is in variable line.
    }
}

为了尝试用Java创建尾部,请参阅:

For my attempt to create a tail in Java see:

  • Method examineFile(…) in https://github.com/AugustusKling/yield/blob/master/src/main/java/yield/input/file/FileMonitor.java
  • The above is used by https://github.com/AugustusKling/yield/blob/master/src/main/java/yield/input/file/FileInput.java to create a tail operation. The queue.feed(lineContent) passes line content for processing by listeners and would equal your this.parse(…).

您可以从该代码中获取灵感,也可以只复制您需要的部件。如果您发现任何我不知道的问题,请告诉我。

Feel free to take inspiration from that code or simply copy the parts you require. Let me know if you find any issues that I'm not aware of.

这篇关于Java:在不锁定文件的情况下打开和读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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