>  기사  >  Java  >  Apache Tika를 사용하여 Zip 아카이브 내에서 여러 파일 형식의 콘텐츠를 어떻게 읽나요?

Apache Tika를 사용하여 Zip 아카이브 내에서 여러 파일 형식의 콘텐츠를 어떻게 읽나요?

Mary-Kate Olsen
Mary-Kate Olsen원래의
2024-10-28 21:20:30715검색

How Do I Read Content from Multiple File Types Within a Zip Archive Using Apache Tika?

Apache Tika를 사용하여 Zip 내 파일에서 콘텐츠 읽기

과제:

당신은 다음과 같은 Java 프로그램을 작성하고자 합니다. Apache Tika를 사용하여 zip 아카이브 내의 여러 파일 내용을 추출하고 읽습니다. 특히 zip 파일에는 텍스트, PDF 및 docx 파일이 혼합되어 있습니다.

해결책:

public class ZipContentExtractor {

    public static void main(String[] args) throws IOException, SAXException, TikaException {
        File zipFile = new File("C:\Users\xxx\Desktop\abc.zip");

        try (ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(zipFile))) {
            ZipEntry entry;
            while ((entry = zipInputStream.getNextEntry()) != null) {
                // Checking file types
                if (entry.getName().endsWith(".txt") || entry.getName().endsWith(".pdf") || entry.getName().endsWith(".docx")) {
                    // Handling text files
                    if (entry.getName().endsWith(".txt")) {
                        BodyContentHandler textHandler = new BodyContentHandler();
                        Parser parser = new AutoDetectParser();
                        parser.parse(zipInputStream, textHandler, new Metadata(), new ParseContext());
                        System.out.println("TXT file content: " + textHandler.toString());
                    }
                    // Handling PDF files
                    else if (entry.getName().endsWith(".pdf")) {
                        Metadata metadata = new Metadata();
                        Parser parser = new PDFParser();
                        parser.parse(zipInputStream, new StreamingContentHandler(), metadata, new ParseContext());
                        System.out.println("PDF file content: " + metadata.get("xmpDM:documentID"));
                    }
                    // Handling DOCX files
                    else {
                        BodyContentHandler textHandler = new BodyContentHandler();
                        Parser parser = new OOXMLParser();
                        parser.parse(zipInputStream, textHandler, new Metadata(), new ParseContext());
                        System.out.println("DOCX file content: " + textHandler.toString());
                    }
                }
            }
        }
    }
}

설명:

  • 코드는 zip 파일의 항목을 반복합니다.
  • 각 항목에 대해 파일 형식을 확인하고 파일 확장자에 따라 적절하게 처리합니다.
  • 의 경우 텍스트 파일의 경우 Apache Tika의 AutoDetectParser는 콘텐츠를 문자열로 구문 분석하는 데 사용됩니다.
  • PDF 파일의 경우 PDFParser는 문서 ID와 같은 메타데이터를 추출하는 데 사용됩니다.
  • DOCX 파일의 경우, OOXMLParser는 콘텐츠를 문자열로 구문 분석하는 데 사용됩니다.

위 내용은 Apache Tika를 사용하여 Zip 아카이브 내에서 여러 파일 형식의 콘텐츠를 어떻게 읽나요?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.