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

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());

}

}

}

解决方案

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.

}

}

For my attempt to create a tail in Java see:

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值