哪位达人帮我看看,为何如此申请文件锁之后无法用该(申请文件锁的)通道来读写该文件?其原理是什么?
(该文件已有内容被写入)import java.io.File;
import java.io.RandomAccessFile;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;public class test7
{
public static void main(String[] args)
{
File file = new File("c:\\exFile\\NameAddress\\test7.txt");
File fileTmp = null;
RandomAccessFile randomAccessFile = null;
FileInputStream fileStream = null;
FileChannel ioChannel = null;
FileChannel inputChannel = null;
FileLock fileLock = null;

try
{
randomAccessFile = new RandomAccessFile(file, "rws");
}
catch(FileNotFoundException e)
{
e.printStackTrace(System.err);
System.out.println("异常!将被读写的文件不存在!程序执行将被终止!");
System.exit(-1);
}
ioChannel = randomAccessFile.getChannel();
fileTmp = new File("c:\\exFile\\NameAddress\\test752727.tmp");
try
{
fileStream = new FileInputStream(fileTmp);
}
catch(FileNotFoundException e)
{
e.printStackTrace(System.err);
System.out.println("异常!将被读取的临时文件不存在!程序执行将被终止!");
System.exit(-3);
}
inputChannel = fileStream.getChannel();
try
{
fileLock = ioChannel.tryLock(0L, Long.MAX_VALUE, true);
}
catch(IOException e)
{
e.printStackTrace(System.err);
System.out.println("异常!无法申请到文件锁!程序执行将被终止!");
System.exit(-4);
}
try
{
long bytesRead = 0L;
long bytesHas = inputChannel.size();
while(bytesRead < bytesHas)
{
bytesRead += ioChannel.transferFrom(inputChannel, bytesRead, (bytesHas - bytesRead));
}
}
catch(IOException e)
{
e.printStackTrace(System.err);
System.out.println("异常!无法复制文件内容!程序执行将被终止!");
System.exit(-5);
}
System.out.println("复制完成!程序执行正常结束!");
System.exit(0);
}
}

解决方案 »

  1.   

    把这句fileLock = ioChannel.tryLock(0L, Long.MAX_VALUE, true); 
    改为:
    fileLock = ioChannel.tryLock(0L, Long.MAX_VALUE, false); //独占锁定
      

  2.   

    我把你的程序试了一下,没发现你说的问题,倒是发现你的临时文件没有判断是否存在,会报错,也许你指的就是这个错误?解决方法:
    fileTmp = new File("c:\\exFile\\NameAddress\\test752727.tmp");
    if (!fileTmp.exists()){
    try{
    fileTmp.createNewFile();
    }catch(Exception ex){
    System.out.println("异常!临时文件不存在,且不允许创建!");

    }
    }
      

  3.   

    To 2楼:
       这个临时文件已经存在,且已经有内容被写了进去,这是这个程序运行的前提条件。当然,这是由于我有所疏漏。我想可以在该目录下新建一个有内容的文件,用来代替test752727.tmp。这样就能重现我遇到的异常了。(我用的是JDK1.5)