Java:在不锁定文件的情况下打开和读取文件

rog*_*780 10 java filelock java-io

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

这是我目前使用的代码:

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());
        }           
    }       
}
Run Code Online (Sandbox Code Playgroud)

Aug*_*ing 6

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

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.
    }
}
Run Code Online (Sandbox Code Playgroud)

对于我尝试用Java创建尾部,请参阅:

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