使用 FileInputStream、FileOutputStream 和 RandomAccessFile 锁定 XLSX 文件以进行读写

Locking an XLSX file for reading and writing with FileInputStream, FileOutputStream, and RandomAccessFile

我有一个 excel,我想在每个分叉进程读取和写入它时将其锁定。 Apache poi 要求我使用 FileInputStreamFileOutputStream 来读取和写入该文件,但是我看到的所有用于锁定文件以进行读取和写入的示例都使用 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();

    }

不要在您的实际共享文件上使用 RandomAccessFileFileChannelFileLock,而是尝试创建并锁定一个单独的虚拟文件。这样,成功的进程将不会在 Excel 文件上看到异常锁或其他 activity。