神奇的文件锁定

映射的文件通道I/O和文件锁定示例:
 1import java.io.*;
 2import java.nio.*;
 3import java.nio.channels.*;
 4
 5/** A class used to demonstrate mapped file channel i/o
 6  * and file locking
 7  */

 8public class CaseReverserNIO {
 9   /** Method reverses the case of characters in a file
10     * @param args[0] The name of the input/output file 
11     * @throws IOException 
12     *   if an error is detected opening or closing the
13     *   file
14     */

15   public static void main( String[] args ) throws IOException {
16      RandomAccessFile raf = null;
17      FileChannel fc = null;
18      FileLock lock = null;  //
19      if ( args.length >= 1 ) try {
20         File f = new File( args[0] );
21         raf = new RandomAccessFile( f, "rw" );
22         fc = raf.getChannel();  //获得管道
23         lock = fc.lock();   //加锁
24         MappedByteBuffer mbb
25            = fc.map( FileChannel.MapMode.READ_WRITE, 0,
26                      fc.size() );
27         char c;
28         for ( int i = 0; i < mbb.limit(); i++ ) {
29            c = (char) mbb.get( i );
30            if ( Character.isLowerCase( c ) ) {
31               mbb.put( i, 
32                        (byte) Character.toUpperCase( c ) );
33            }
 else if ( Character.isUpperCase( c ) ) {
34               mbb.put( i,
35                        (byte) Character.toLowerCase( c ) );
36            }

37         }

38      }

39      catch( IOException iox ) {
40         System.out.println( iox );
41      }

42      finally {
43         fc.close();
44         raf.close();
45         lock.release();  //解锁
46      }
 else {
47         System.out.println( "Provide an input filename" );
48      }

49   }

50}

注意:
java.nio提供了一种方法通过进程锁定一个文件;
没有写动作;
另外,修改后的文件的最后修改时间不变(恐怖)。
原文地址:https://www.cnblogs.com/bankey/p/353642.html