java.nio.channels.NonWritableChannelException at sun.nio.ch.FileChannelImpl.lock(FileChannelImpl.java:739) at java.nio.channels.FileChannel.lock(FileChannel.java:865) at com.yb.filework.thread.ReplyThread.work(ReplyThread.java:112) at com.yb.filework.thread.ReplyThread.run(ReplyThread.java:155) at com.yb.filework.thread.ReplyThread.main(ReplyThread.java:164)
http://blog.sina.com.cn/u/46e73e77010001cj
有时候,我们需要以独占的方式访问某个文件,因此,需要在打开文件时,对文件上锁,以防其他人或进程也访问该文件。Java本身提供了俩种锁文件的方式: 方式一:用RandomAccessFile类操作文件 RandomAccessFile的open方法,提供了参数,实现以独占的方式打开文件: new RandomAccessFile(file, "rws") 其中的“rws”参数中,rw代表读写方式,s代表同步方式,也就是锁。这种方式打开的文件,就是独占方式。方式二:用文件通道(FileChannel)的锁功能如:RandomAccessFile raf = new RandomAccessFile(new File("c:\\test.txt"), "rw"); FileChannel fc = raf.getChannel(); FileLock fl = fc.tryLock(); if (fl.isValid()) { System.out.println("get the lock!");但这俩种方式,都只能通过RandomAccessFile访问文件,如果只能通过InputStream来访问文件,如用DOM分析XML文件,怎么办呢? 其实,FileInputStream对象,也提供了getChannel方法,只是缺省的getChannel方法,不能锁住文件,所以,如果需要,就必须自己重写一个getChannel方法,如: public FileChannel getChannel(FileInputStream fileIn, FileDescriptor fd) { FileChannel channel = null; synchronized (fileIn) { channel = FileChannelImpl.open(fd, true, true, fileIn); return channel; } }其实,主要是打开文件的第三个参数控制了对文件的操作模式,如果设置为false,就不能锁住文件,缺省的getChannel方法,就是false,因此,不能锁住文件。
方式一:用RandomAccessFile类操作文件
RandomAccessFile的open方法,提供了参数,实现以独占的方式打开文件:
new RandomAccessFile(file, "rws")
其中的“rws”参数中,rw代表读写方式,s代表同步方式,也就是锁。这种方式打开的文件,就是独占方式。方式二:用文件通道(FileChannel)的锁功能如:RandomAccessFile raf = new RandomAccessFile(new File("c:\\test.txt"), "rw"); FileChannel fc = raf.getChannel();
FileLock fl = fc.tryLock(); if (fl.isValid()) {
System.out.println("get the lock!");但这俩种方式,都只能通过RandomAccessFile访问文件,如果只能通过InputStream来访问文件,如用DOM分析XML文件,怎么办呢?
其实,FileInputStream对象,也提供了getChannel方法,只是缺省的getChannel方法,不能锁住文件,所以,如果需要,就必须自己重写一个getChannel方法,如:
public FileChannel getChannel(FileInputStream fileIn, FileDescriptor fd) {
FileChannel channel = null;
synchronized (fileIn) {
channel = FileChannelImpl.open(fd, true, true, fileIn);
return channel;
}
}其实,主要是打开文件的第三个参数控制了对文件的操作模式,如果设置为false,就不能锁住文件,缺省的getChannel方法,就是false,因此,不能锁住文件。