FileLock
来源:互联网 发布:windows 10卸载edge 编辑:程序博客网 时间:2024/05/16 10:48
import org.junit.Ignore;import org.junit.Test;import java.io.File;import java.io.RandomAccessFile;import java.nio.channels.FileLock;public class FileLockTest { @Test public void testFileLock2() throws Exception { File file = new File("/tmp/stamp.txt"); RandomAccessFile out = new RandomAccessFile(file, "rw"); if (!file.exists()) file.createNewFile(); FileLock fileLock = out.getChannel().tryLock(); if (null != fileLock) { out.writeUTF(NLPConstants.DEFAULT_TIME_FORMATTER.print(System.currentTimeMillis())); fileLock.release(); out.close(); } else { System.err.println("this file has been open but other person!"); } //////in RandomAccessFile in = new RandomAccessFile(file, "rw"); if (!file.exists()) System.err.println("not exists"); FileLock fileLockIn = in.getChannel().tryLock(); if (null != fileLockIn) { String ret = in.readUTF(); System.out.println(ret); fileLockIn.release(); in.close(); } else { System.err.println("this file has been open but other person!"); } }}