![](/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.