【问题标题】:IOException: The process cannot access the file because another process has locked a portion of the fileIOException:该进程无法访问该文件,因为另一个进程已锁定该文件的一部分
【发布时间】:2017-11-01 14:46:50
【问题描述】:

我打开了一个文件,然后我锁定了一个文件区域,我希望更新一个值,然后将其重写回文件。尝试写入已锁定的文件时收到以下错误消息:

java.io.IOException: The process cannot access the file because another 
process has locked a portion of the file

代码示例:

// Now lets get a lock on the first 10 characters       
try( RandomAccessFile raFile    = new RandomAccessFile( cbooking, "rw" );
FileChannel channel         = raFile.getChannel(); 
FileLock lock           = channel.lock( 1 , 10, true)   ) {  
    // Write the new value to the file
    byte[] bytes = "           ".getBytes();
    raFile.write( bytes );
}
catch ( IOException e) {
    e.printStackTrace();
    // TODO Add logging - Could not gain character lock on the file!
    return false;
}

任何意见表示赞赏。

【问题讨论】:

  • 你找到答案了吗?我在 Windows 上遇到了同样的事情,这有点让人生气

标签: java ioexception


【解决方案1】:

如果您认为它确实没有被另一个实例锁定,请尝试 FileChannel.open 而不是通过 RandomAccessFile 获取频道

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-20
    • 2020-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-18
    • 2010-12-10
    相关资源
    最近更新 更多