如何解決java.util.zip.ZipFile解壓后被java占用問題
java.util.zip.ZipFile解壓后被java占用
在使用jdk自帶zip解壓工具解壓文件時,調用ZipFile的getInputStream(ZipEntry entry)方法獲取實體輸入流后,正常關閉getInputStram返回的輸入流。
zip文件仍然被占用,導致java刪除zip文件失敗的問題。
解決方法
在解壓完成后調用ZipFile的close()方法關閉所有已打開的輸入流。
原因:根據(jù)源碼(jdk1.6)
若壓縮方式為STORED,則 getInputStream返回ZipFileInputStream類的輸入流
該輸入流的close()方法如下:
public void close() {
rem = 0;
synchronized (ZipFile.this) {
if (jzentry != 0 && ZipFile.this.jzfile != 0) {
freeEntry(ZipFile.this.jzfile, jzentry);
jzentry = 0;
}
}
}
// freeEntry releases the C jzentry struct.
private static native void freeEntry(long jzfile, long jzentry);若壓縮方式為DEFLATED,則 getInputStream返回InflaterInputStream類的輸入流
該輸入流的close()方法如下:
protected Inflater inf;
/**
* Closes this input stream and releases any system resources associated
* with the stream.
* @exception IOException if an I/O error has occurred
*/
public void close() throws IOException {
if (!closed) {
if (usesDefaultInflater)
inf.end();
in.close();
closed = true;
}
}
public void end() {
synchronized (zsRef) {
long addr = zsRef.address();
zsRef.clear();
if (addr != 0) {
end(addr);
buf = null;
}
}
}
public class Inflater {
private native static void end(long addr);
}而ZipFile類提供的close()方法為:
主要區(qū)別應該在于Store的壓縮方式,執(zhí)行了closeRequested = true 和close(zf),而 ZipFileInputStream只是調用了 freeEntry;
對于 壓縮方式為DEFLATED的情況,還未測試。
/**
* Closes the ZIP file.
* <p> Closing this ZIP file will close all of the input streams
* previously returned by invocations of the {@link #getInputStream
* getInputStream} method.
*
* @throws IOException if an I/O error has occurred
*/
public void close() throws IOException {
synchronized (this) {
closeRequested = true;
if (jzfile != 0) {
// Close the zip file
long zf = this.jzfile;
jzfile = 0;
close(zf);
// Release inflaters
synchronized (inflaters) {
int size = inflaters.size();
for (int i = 0; i < size; i++) {
Inflater inf = (Inflater)inflaters.get(i);
inf.end();
}
}
}
}
}總結
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
利用SpringBoot實現(xiàn)RSA+AES混合加密
用戶注冊時,密碼明文傳輸被攔截?支付信息在傳輸過程中被竊???或者敏感數(shù)據(jù)在接口調用時被中間人攻擊?再或者App被反編譯,接口參數(shù)被破解?今天我們就來聊聊如何用SpringBoot實現(xiàn)RSA+AES混合加密,讓你的接口數(shù)據(jù)傳輸更安全,需要的朋友可以參考下2026-01-01
knife4j+springboot3.4異常無法正確展示文檔
本文主要介紹了knife4j+springboot3.4異常無法正確展示文檔,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2025-01-01
線程池ThreadPoolExecutor并行處理實現(xiàn)代碼
這篇文章主要介紹了線程池ThreadPoolExecutor并行處理實現(xiàn)代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-11-11

