在Java中如何给文件加锁?如何给确认文件是否被加锁?做个测试先。
Test.java
- package me.test;
-
-
import java.io.File;
-
import java.io.FileOutputStream;
-
import java.io.IOException;
-
import java.nio.channels.FileLock;
-
import java.nio.channels.OverlappingFileLockException;
-
-
public class Test {
-
public static void main(String[] args) throws InterruptedException {
-
// 先启动读取
-
R r = new R();
-
r.start();
-
-
// 再启动写入
-
Thread.sleep(1000 * 2);
-
W w = new W();
-
w.start();
-
Thread.sleep(1000 * 2);
-
System.exit(0);
-
}
-
-
// 检查文件是否被锁(通过尝试对该文件追加排他锁)
-
public static boolean i***clusivelyLocked(File f) throws IOException {
-
FileOutputStream out = new FileOutputStream(f);
-
FileLock lock = null;
-
try {
-
lock = out.getChannel().tryLock();
-
if (lock != null) {
-
lock.release();
-
return false; // Has not been locked yet.
-
}
-
} catch (OverlappingFileLockException e) {
-
return true; // Already locked by same JVM
-
} finally {
-
out.close();
-
}
-
-
return true; // Already locked by ohter JVM or applications
-
}
-
-
// 写入一个文件并加锁()
-
public static class W extends Thread {
-
@Override
-
public void run() {
-
try {
-
File f = new File("C:/123.txt");
-
FileOutputStream out = new FileOutputStream(f);
-
// 加锁(独占)
-
FileLock lock = out.getChannel().lock();
-
System.out.println("W: lock.isShared() = " + lock.isShared());
-
System.out.println("W: lock.isValid() = " + lock.isValid());
-
out.write("Hello World~".getBytes());
-
while (true) {
-
Thread.sleep(1000);
-
}
-
// out.close(); // 一旦close,lock.isValid() == false;
-
} catch (Exception e) {
-
e.printStackTrace();
-
}
-
}
-
}
-
-
// 读取一个文件并加锁
-
public static class R extends Thread {
-
@Override
-
public void run() {
-
try {
-
File f = new File("C:/123.txt");
-
while (true) {
-
System.out.println("R: canRead() = " + f.canRead()
-
+ ", isLocked() = " + i***clusivelyLocked(f));
-
Thread.sleep(1000);
-
}
-
} catch (Exception e) {
-
e.printStackTrace();
-
}
-
}
-
}
-
}
命令行输出结果:
- R: canRead() = true, isLocked() = false
-
R: canRead() = true, isLocked() = false
-
W: lock.isShared() = false
-
W: lock.isValid() = true
-
R: canRead() = true, isLocked() = true
-
R: canRead() = true, isLocked() = true
-
R: canRead() = true, isLocked() = true
阅读(1288) | 评论(0) | 转发(0) |