![](/img/trans.png)
[英]Reading and writing into the same file with FileInputStream and FileOutputStream
[英]Locking an XLSX file for reading and writing with FileInputStream, FileOutputStream, and RandomAccessFile
我有一个 excel,我想在每个分叉进程读取和写入它时锁定它。 Apache poi 要求我使用FileInputStream
和FileOutputStream
来读取和写入该文件,但是我看到的所有用于锁定文件以进行读取和写入的示例都为此使用RandomAccessFile
,但是当我这样做时,当我调用workbook.write(os);
我得到一个org.apache.poi.openxml4j.exceptions.OpenXML4JRuntimeException
并且excel 损坏了。 这是一些代码:
try {
RandomAccessFile raf = new RandomAccessFile(path,"rw");
FileChannel channel = raf.getChannel();
FileLock lock = channel.lock(0L,Long.MAX_VALUE,true);
FileInputStream is = new FileInputStream(path);
XSSFWorkbook workbook = new XSSFWorkbook(is);
XSSFSheet sheet = workbook.getSheet(env.toUpperCase());
Iterator<Row> rowIterator = sheet.iterator();
//skip headers
rowIterator.next();
while (rowIterator.hasNext())
{
//reading and editing values in excel
}
is.close();
FileOutputStream os = new FileOutputStream(path);
workbook.write(os);
workbook.close();
os.close();
lock.release();
channel.close();
raf.close();
}
不要在实际的共享文件上使用RandomAccessFile
, FileChannel
和FileLock
,而是尝试创建并锁定一个单独的虚拟文件。 这样,成功的过程将不会在Excel文件上看到异常的锁或其他活动。
当你说锁定一个虚拟文件时,你是什么意思? 但是如果我们锁定一个单独的虚拟文件,文件的实际读取将如何被锁定
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.