java对文件加锁

详见:http://blog.yemou.net/article/query/info/tytfjhfascvhzxcyt208

在对文件操作过程中,有时候需要对文件进行加锁操作,防止其他线程访问该文件。对文件的加锁方法有两种:

第一种方法:使用RandomAccessFile类操作文件。

在java.io.RandomAccessFile类的open方法,提供了参数实现独占的方式打开文件:

        RandomAccessFile raf = new RandomAccessFile(file, "rws");

其中的“rws”参数,rw代表读取和写入,s代表了同步方式,也就是同步锁。这种方式打开的文件,就是独占方式的。

第二种方法:使用sun.nio.FileChannel对文件进行加锁。

代码:

      RandomAccessFile raf = new RandomAccessFile("file.txt", "rw");

      FileChannel fc = raf.getChannel();

      FileLock fl = fc.tryLock();

      if(fl.isValid())

          System.out.println("You have got the file lock.");

以上是通过RandomAccessFile来获得文件锁的,那么在写文件的时候如何对文件加锁呢?方法如下:

代码:

        FileOutputStream fos = new FileOutputStream("file.txt");

        FileChannel fc = fos.getChannel(); //获取FileChannel对象

        FileLock fl = fc.tryLock();  //or fc.lock();

        if(null != fl)

             System.out.println("You have got file lock.");

        //TODO write content to file

        //TODO write end, should release this lock

        fl.release(); //释放文件锁  注意:释放锁要在文件写操作之前,否则会出异常

        fos.close;  //关闭文件写操作

如果在读文件操作的时候,对文件进行加锁,怎么操作呢?从API文档中我们可以看到,FileChannel也可以从FileInputStream中直接获得,但是这种直接获得FileChannel的对象直接去操作FileLock会报异常NonWritableChannelException,这样我们又怎么去获得文件锁呢?需要自己去实现getChannel方法,代码如下:

           private static FileChannel getChannel(FileInputStream fin, FileDescriptor fd) {

                  FileChannel channel = null;

                  synchronized(fin){

                        channel = FileChannelImpl.open(fd, true, true, fin);

                        return channel;

                  }

            }

其实,我们看FileInputStream时,发现getChannel方法与我们写的代码只有一个地方不同,即open方法的第三个参数不同,如果设置为false,就不能锁住文件了。缺省的getChannel方法,就是false,因此,不能锁住文件。

原文地址:https://www.cnblogs.com/grefr/p/6094917.html