import java.io.File;
import java.io.FileInputStream;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;public class TestFileLock {    public static void main(String[] args) {
testFileLock();    }
    public static void testFileLock(){
       try{
          File file = new File("d:\\test.xls");
          if(!file.exists())
             file.createNewFile()
           while(true){
              try{
                //FileInputStream fis = new FileInputStream(file);
                  RandomAccessFile raf = new RandomAccessFile(file, "rw");
                  FileChannel fc = raf.getChannel();
                  FileLock fl = fc.lock();
                  if(fl.isValid())
                      System.out.println("locked");
                   fl.release();
                        System.out.println(fl.isValid());
                    break;
                }catch(Exception e){
                    e.printStackTrace();
                    Thread.sleep(10);
                }
            }
            System.out.println("while breaked...");
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}
上面的程序为什么获取RandomAccessFile流通向底层文件的锁不会出现异常,假如RandomAccessFile换成
FileInputStream流也就是把try中的第一句去掉注释,第二句加注释,获取通道的对象该一下,就会出现
java.nio.channels.NonWritableChannelException
at sun.nio.ch.FileChannelImpl.lock(FileChannelImpl.java:969)
at java.nio.channels.FileChannel.lock(FileChannel.java:1052)
at filelockIO.TestFileLock.testFileLock(TestFileLock.java:35)
at filelockIO.TestFileLock.main(TestFileLock.java:19)
检查之后发现是 FileLock fl = fc.lock()这句话异常,为什么不能给字节输入流加文件锁???