import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.channels.FileLock;
public class FileReaderLock {
public static void main(String[] args) throws Exception {
FileInputStream fos = new FileInputStream("file.txt");
//获取文件锁 FileLock 对象
FileLock fl = fos.getChannel().tryLock();
//下面两个都会报错
FileOutputStream fos1 = new FileOutputStream("file.txt");
// fos1.write(1);
FileInputStream fis = new FileInputStream("file.txt");
// fis.read();
//tryLock是尝试获取锁,有可能为空,所以要判断
if (fl != null) {
System.out.println("Locked File");
Thread.sleep(100);
fl.release();//释放锁
System.out.println("Released Lock");
}
fos.close();
}
}