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

S J*_*esh 62 java zip extract apache-tika

我正在尝试创建一个简单的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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Rod*_*aki 159

如果您想知道如何从每个文件中获取文件内容,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);
    }
}
Run Code Online (Sandbox Code Playgroud)

一旦你有了InputStream,你可以随意阅读它.

  • 不要忘记关闭inputStream和ZipFile以避免资源泄漏:). (17认同)
  • zipFile.entries(); 没有为zipFile类型定义的条目函数 (3认同)
  • 有没有办法将byte []数组传递给ZipFile(content.getBytes())的构造方法?如果没有,我们该怎么做? (2认同)

Lor*_*igs 39

从Java 7开始,NIO Api提供了一种更好,更通用的方式来访问Zip或Jar文件的内容.实际上,它现在是一个统一的API,允许您像普通文件一样处理Zip文件.

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

在Java 8中:

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));
            });
}
Run Code Online (Sandbox Code Playgroud)

在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);
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这既令人敬畏又疯狂. (9认同)
  • `FileSystem` 应该在操作后关闭。 (2认同)
  • 在Java 8版本中,`Files.walk(root)`引发IOException,该异常无法通过lambda传播。 (2认同)

Nis*_*hth 10

由于条件while,循环可能永远不会破坏:

while (entry != null) {
  // If entry never becomes null here, loop will never break.
}
Run Code Online (Sandbox Code Playgroud)

而不是在null那里检查,你可以试试这个:

ZipEntry entry = null;
while ((entry = zip.getNextEntry()) != null) {
  // Rest of your code
}
Run Code Online (Sandbox Code Playgroud)