gpt4 book ai didi

java - 从 Zip 文件中的文件中读取内容

转载 作者:IT老高 更新时间:2023-10-28 13:54:16 28 4
gpt4 key购买 nike

我正在尝试创建一个简单的 java 程序,该程序从 zip 文件中的文件中读取和提取内容。 Zip 文件包含 3 个文件(txt、pdf、docx)。我需要阅读所有这些文件的内容,为此我使用 Apache Tika

有人可以帮我实现这个功能吗?到目前为止我已经尝试过,但没有成功

代码片段

public class SampleZipExtract {


public static void main(String[] args) {

List<String> tempString = new ArrayList<String>();
StringBuffer sbf = new StringBuffer();

File file = new File("C:\\Users\\xxx\\Desktop\\abc.zip");
InputStream input;
try {

input = new FileInputStream(file);
ZipInputStream zip = new ZipInputStream(input);
ZipEntry entry = zip.getNextEntry();

BodyContentHandler textHandler = new BodyContentHandler();
Metadata metadata = new Metadata();

Parser parser = new AutoDetectParser();

while (entry!= null){

if(entry.getName().endsWith(".txt") ||
entry.getName().endsWith(".pdf")||
entry.getName().endsWith(".docx")){
System.out.println("entry=" + entry.getName() + " " + entry.getSize());
parser.parse(input, textHandler, metadata, new ParseContext());
tempString.add(textHandler.toString());
}
}
zip.close();
input.close();

for (String text : tempString) {
System.out.println("Apache Tika - Converted input string : " + text);
sbf.append(text);
System.out.println("Final text from all the three files " + sbf.toString());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TikaException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

最佳答案

如果您想知道如何从每个 ZipEntry 获取文件内容,这实际上非常简单。这是一个示例代码:

public static void main(String[] args) throws IOException {
ZipFile zipFile = new ZipFile("C:/test.zip");

Enumeration<? extends ZipEntry> entries = zipFile.entries();

while(entries.hasMoreElements()){
ZipEntry entry = entries.nextElement();
InputStream stream = zipFile.getInputStream(entry);
}
}

一旦你有了 InputStream,你就可以随心所欲地阅读它。

关于java - 从 Zip 文件中的文件中读取内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15667125/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com