FileLock

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!");
        }

    }
}

發佈了409 篇原創文章 · 獲贊 21 · 訪問量 85萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章