最近有Java解壓縮的需求,java.util.zip實在不好用,對中文支持也不行。所以選擇了強大的TrueZIP,使用時遇到了一個問題,做個記錄。
解壓縮代碼如下:
ArchiveDetector detector = new DefaultArchiveDetector(ArchiveDetector.ALL,
new Object[] { "zip", new CheckedZip32Driver("GBK") } );
File zipFile = new File("zipFile", detector);
File dst = new File("dst");
// 解壓縮
zipFile.copyAllTo(dst);
代碼十分簡潔,注意這個File是
de.schlichtherle.io.File
不是
java.io.File
當(dāng)處理完業(yè)務(wù)要刪除這個Zip File時,問題出現(xiàn)了:
這個文件刪不掉!!!
把自己的代碼檢查了好久,確認(rèn)沒問題后,開始從TrueZIP下手,發(fā)現(xiàn)它有特殊的地方的,是提示過的:
File file = new File(“archive.zip”); // de.schlichtherle.io.File!
Please do not do this instead:
de.schlichtherle.io.File file = new de.schlichtherle.io.File(“archive.zip”);
This is for the following reasons:
1.Accidentally using java.io.File and de.schlichtherle.io.File instances referring to the same path concurrently will result in erroneous behaviour and may even cause loss of data! Please refer to the section “Third Party Access” in the package Javadoc of de.schlichtherle.io for for full details and workarounds.
2.A de.schlichtherle.io.File subclasses java.io.File and thanks to polymorphism can be used everywhere a java.io.File could be used.
原來兩個File不能交叉使用,搞清楚原因了,加這么一句代碼搞定。
zipFile.deleteAll();