JAVA 锁定文件
package com.file;import java.io.FileOutputStream;import java.nio.channels.FileLock;//操作文件锁定的类public class LockFile {public static void fileLock(String file) {// 锁定文件FileOutputStream fous = null;FileLock lock = null;try {fous = new FileOutputStream(file);// 创建文件输出流lock = fous.getChannel().tryLock();// 锁定文件Thread.sleep(60 * 1000);// 本线程锁定1分钟。过后任何程序对该文件的写操作将被禁止} catch (Exception e) {// 捕获异常e.printStackTrace();} finally {try {if (lock != null)lock.release();// 锁释放if (fous != null)fous.close();} catch (Exception e) {System.out.println("出现异常");System.exit(1);}}}public static void main(String[] args) {// java程序的主入口处String file = "F:/poem.txt";System.out.println("锁定文件:");fileLock(file);// 调用方法锁定文件}}?