当前位置: 首页 > 知识库问答 >
问题:

从Zip文件中读取内容

秦钟展
2023-03-14

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

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

代码片段

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();
        }
    }
}

共有3个答案

东方吕恭
2023-03-14

由于中的条件,循环可能永远不会中断:

while (entry != null) {
  // If entry never becomes null here, loop will never break.
}

这里的null检查不同,您可以尝试:

ZipEntry entry = null;
while ((entry = zip.getNextEntry()) != null) {
  // Rest of your code
}
汤念
2023-03-14

从Java7开始,NIO Api提供了一种更好、更通用的方式来访问Zip或Jar文件的内容。实际上,它现在是一个统一的应用编程接口,允许您像对待普通文件一样对待Zip文件。

为了在此API中提取zip文件中包含的所有文件,您需要执行以下操作:

在Java8:

private void extractAll(URI fromZip, Path toDirectory) throws IOException{
    FileSystems.newFileSystem(fromZip, Collections.emptyMap())
            .getRootDirectories()
            .forEach(root -> {
                // in a full implementation, you'd have to
                // handle directories 
                Files.walk(root).forEach(path -> Files.copy(path, toDirectory));
            });
}

java 7中:

private void extractAll(URI fromZip, Path toDirectory) throws IOException{
    FileSystem zipFs = FileSystems.newFileSystem(fromZip, Collections.emptyMap());

    for(Path root : zipFs.getRootDirectories()) {
        Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) 
                    throws IOException {
                // You can do anything you want with the path here
                Files.copy(file, toDirectory);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) 
                    throws IOException {
                // In a full implementation, you'd need to create each 
                // sub-directory of the destination directory before 
                // copying files into it
                return super.preVisitDirectory(dir, attrs);
            }
        });
    }
}
慕仲渊
2023-03-14

如果你想知道如何从每个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);
    }
}

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

 类似资料:
  • 问题内容: 我正在尝试创建一个简单的Java程序,该程序从zip文件中的文件读取和提取内容。压缩文件包含3个文件(txt,pdf,docx)。我需要阅读所有这些文件的内容,并且为此使用了Apache Tika。 有人可以帮我实现此功能。到目前为止,我已经尝试过了,但是没有成功 代码段 问题答案: 如果你想知道如何从每个文件中获取文件内容,ZipEntry那实际上很简单。这是一个示例代码: 一旦拥有

  • 问题内容: 我从SUN网站(http://java.sun.com/developer/technicalArticles/Programming/compression/)找到了示例,但是它返回BufferedOutputStream。但是我想将ZipEntry文件作为InputStream,然后处理下一个文件。那可能吗?我的程序无法访问硬盘,因此它甚至无法临时保存文件。 问题答案: 好吧,只需

  • 问题内容: 我必须使用SFTP从ZIP存档(只有一个文件,我知道它的名称)中获取文件内容。我唯一拥有的是ZIP的。大多数示例说明如何使用以下语句获取内容: 但是正如我所说,我的本地计算机上没有ZIP文件,也不想下载它。是够看了? UPD: 这是我的方法: 问题答案: 好吧,我已经做到了: 它可以帮助我阅读ZIP的内容而无需写入另一个文件。

  • 我必须使用SFTP从ZIP存档(只有一个文件,我知道它的名称)获取文件内容。我唯一拥有的是ZIP的InputStream。大多数示例显示了如何使用此语句获取内容: 但正如我所说,我的本地机器上没有ZIP文件,我不想下载它。输入流是否足以读取? UPD:我就是这样做的:

  • 问题内容: 我的情况是我有一个包含一些文件(txt,png,…)的zip文件,我想直接按它们的名称读取它,我已经测试了以下代码,但没有结果(NullPointerExcepion): resources 是一个包, zipfile 是一个zip文件。 问题答案: 如果您可以确定您的zip文件永远不会打包在另一个jar中,则可以使用以下方法: 要么: 否则,您的选择是: 使用ZipInputStre

  • 我有一个zip文件(在一个jar文件中),我想读取init。我知道我可以使用getResourceAsStream(…)轻松读取txt文件,避免“URI不分层”错误。但现在确定我该如何为zip文件做到这一点。 下面是我的代码,但当我将代码导出到runnable jar并运行它时,它会抛出“URI非层次错误”。