TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
文件锁定初看起来可能让人迷惑。它似乎指的是防止程序或者用户访问特定文件。事实上,文件锁就像常规的 java 对象锁 ? 它们是 劝告式的(advisory) 锁。它们不阻止任何形式的数据访问,相反,它们通过锁的共享和获取赖允许系统的不同部分相互协调。
您可以锁定整个文件或者文件的一部分。如果您获取一个排它锁,那么其他人就不能获得同一个文件或者文件的一部分上的锁。如果您获得一个共享锁,那么其他人可以获得同一个文件或者文件一部分上的共享锁,但是不能获得排它锁。
文件锁定并不总是出于保护数据的目的。例如,您可能临时锁定一个文件以保证特定的写操作成为原子的,而不会有其他程序的干扰。 大多数操作系统提供了文件系统锁,但是它们并不都是采用同样的方式。有些实现提供了共享锁,而另一些仅提供了排它锁。事实上,有些实现使得文件的锁定部分不可访问,尽管大多数实现不是这样的。
在java nio中提供了文件锁的功能,这样当一个线程将文件锁定之后,其他线程是无法操作此文件的,要进行文件的锁定操作,则要使用FileLock类来完成,此类的对象需要依靠FileChannel进行实例化操作。 
关于锁定的方式: 1 共享锁:允许多个线程进行文件的读取操作
2 独占锁: 只允许一个线程进行文件的读/写操作 这个程序是将a.txt文件锁定60秒
- import java.io.*;
- import java.nio.channels.FileChannel;
- public class FileLock {
- public static void main(String[] args) throws Exception {
- String path = FileLock.class.getClassLoader().getResource("a.txt").getPath();
- File file = new File(path);
-
- RandomAccessFile raf = new RandomAccessFile(file, "rw");
- FileChannel channel = raf.getChannel();
- java.nio.channels.FileLock lock = channel.tryLock();
- //锁定60秒
- Thread.sleep(60*1000);
- //释放
- lock.release();
- //close
- channel.close();
- raf.close();
- }
- }
复制代码 接下来立即运行:读 a.txt文件
- import java.io.*;
- import java.nio.channels.FileChannel;
- import java.nio.ByteBuffer;
- public class ReadFile {
-
- public static void main(String[] args) throws Exception {
- String path = FileLock.class.getClassLoader().getResource("a.txt").getPath();
- File file = new File(path);
-
- FileInputStream ins = new FileInputStream(file);
-
- FileChannel fIns = ins.getChannel();
-
- ByteBuffer buffer = ByteBuffer.allocate(1024);
-
- while (true) {
- buffer.clear();
- int r = fIns.read(buffer);
- if(r == -1){
- break;
- }
- buffer.flip();
- out(buffer);
- }
-
- }
-
- public static void out(ByteBuffer buffer){
- for (int i = 0; i < buffer.limit(); i++) {
- System.out.print(buffer.get());
- }
- }
-
- }
复制代码 C:ex>java ReadFile
Exception in thread "main" java.io.IOException: 另一个程序已锁定文件的一部分,进 程无法访问。
at sun.nio.ch.FileDispatcherImpl.read0(Native Method)
at sun.nio.ch.FileDispatcherImpl.read(FileDispatcherImpl.java:55)
at sun.nio.ch.IOUtil.readIntoNativeBuffer(IOUtil.java:218)
at sun.nio.ch.IOUtil.read(IOUtil.java:191)
at sun.nio.ch.FileChannelImpl.read(FileChannelImpl.java:143)
at ReadFile.main(ReadFile.java:18)
源码下载:http://file.javaxxz.com/2014/10/31/235808468.zip |
|