如何防止用Java读取和处理文件时被覆盖的文件? [英] How to prevent file from being overridden when reading and processing it with Java?

查看:276
本文介绍了如何防止用Java读取和处理文件时被覆盖的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要用Java读取和处理一些大文件,而且我想知道,如果有一些合理的方法来保护文件,以免在读取时遇到其他进程的覆盖;处理它?<​​/ p>

也就是说,使它成为只读的方式,保持它打开或什么...

这将在Windows环境下完成。


Touko

解决方案

你想要一个 FileLock

  FileChannel channel = new RandomAccessFile(C:\\foo, RW)getChannel(); 

//尝试获取没有阻塞的锁。这个方法返回
// null,如果文件已经被锁定,则抛出一个异常。
FileLock lock = channel.tryLock();

// ...

//释放
lock.release();

为了简单起见,我省略了一个enclosng try / finally块,但是不应该在您的生产中代码

I'd need to read and process somewhat large file with Java and I'd like to know, if there is some sensible way to protect the file that it wouldn't be overwritten by other processes while I'm reading & processing it?

That is, some way to make it read-only, keep it "open" or something...

This would be done in Windows environment.

br, Touko

解决方案

you want a FileLock:

FileChannel channel = new RandomAccessFile("C:\\foo", "rw").getChannel();

// Try acquiring the lock without blocking. This method returns
// null or throws an exception if the file is already locked.
FileLock lock = channel.tryLock();

// ...  

// release it
lock.release();

for simplicity's sake I've omitted an enclosng try/finally block but you shouldn't in your production code

这篇关于如何防止用Java读取和处理文件时被覆盖的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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