Java如何獲取文件夾下所有壓縮包下指定文件
更新時間:2024年09月26日 08:52:23 作者:java李楊勇
在Java中,通過遍歷文件夾并對壓縮包進行解析,可以實現(xiàn)提取指定文件的功能,如文檔、PDF等,該過程中可增加過濾條件來適應不同需求,例如文件類型或文件名過濾,該方法適用于處理大量數(shù)據(jù)時的文件管理和數(shù)據(jù)提取
Java獲取文件夾下所有壓縮包下指定文件
import java.io.*;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.zip.*;
/**
* Created by LiYangYong on 2023/6/8
*/
public class WordDocExtractor {
public static void main(String[] args) {
String sourceDir = "D:\\李陽勇個人java相關\\安卓"; // 壓縮包所在目錄
String targetDir = "D:\\李陽勇個人java相關\\directory"; // 目標目錄
File dir = new File(sourceDir);
if (!dir.isDirectory()) {
System.out.println("Invalid source directory.");
return;
}
File[] files = dir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".zip") || name.toLowerCase().endsWith(".rar");
}
});
for (File file : files) {
String archiveName = file.getName();
String archivePath = file.getAbsolutePath();
System.out.println("Processing archive: " + archiveName);
// 使用指定的字符集打開壓縮文件
try (ZipFile zipFile = new ZipFile(file, Charset.forName("GBK"))) {
// 獲取壓縮文件中的所有條目
Enumeration<? extends ZipEntry> entries = zipFile.entries();
// 遍歷所有條目
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
String entryName = entry.getName();
// 如果條目是以 .doc 或 .docx 結(jié)尾的文檔文件
if ((entryName.toLowerCase().endsWith(".doc") || entryName.toLowerCase().endsWith(".docx"))) {
// 如果文件名不包含 "數(shù)據(jù)庫文檔"、"開發(fā)文檔"、"開放文檔",且包含 "論文"
if (!entryName.contains("數(shù)據(jù)庫文檔") && !entryName.contains("開發(fā)文檔") && !entryName.contains("開放文檔") && entryName.contains("論文")) {
// 獲取文檔文件名
String docName = entryName.substring(entryName.lastIndexOf('/') + 1);
// 拼接目標路徑
String targetPath = targetDir + "/" + archiveName + "_" + docName;
// 去掉文件名中的 .zip 后綴
targetPath = targetPath.replace(".zip", "");
// 輸出拷貝信息
System.out.println("Copying " + entryName + " to " + targetPath);
// 從壓縮文件中讀取文檔文件內(nèi)容,并寫入目標文件
try (InputStream inputStream = zipFile.getInputStream(entry);
OutputStream outputStream = new FileOutputStream(targetPath)) {
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}實現(xiàn)效果
中間可以自己加一些過濾條件來滿足各種需求。
不管是文檔或其他pdf等

總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
詳解Java中NullPointerException異常的原因和解決辦法
本文主要介紹了詳解Java中NullPointerException異常的原因和解決辦法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-07-07
apollo與springboot集成實現(xiàn)動態(tài)刷新配置的教程詳解
這篇文章主要介紹了apollo與springboot集成實現(xiàn)動態(tài)刷新配置,本文分步驟給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-06-06
SpringBoot項目nohup啟動運行日志過大的解決方案
這篇文章主要介紹了SpringBoot項目nohup啟動運行日志過大的解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-05-05
Spring JDK動態(tài)代理實現(xiàn)過程詳解
這篇文章主要介紹了Spring JDK動態(tài)代理實現(xiàn)過程詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-02-02

