1
我有一个excel,当每个分支进程正在读取和写入时,我想锁定它。 Apache poi要求我使用FileInputStream
和FileOutputStream
来读取和写入该文件,但是我已经看到锁定文件进行读取和写入的所有示例使用RandomAccessFile
,但是当我这样做时,当我拨打workbook.write(os);
时,我得到 org.apache.poi.openxml4j.exceptions.OpenXML4JRuntimeException
和excel变得损坏。下面是一些代码:锁定用FileInputStream,FileOutputStream和RandomAccessFile读写的XLSX文件
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();
}
伟大的建议!尝试这样的事情甚至没有跨过我的脑海。谢谢。 – aoatley