Java 怎么检查doc和docx文件是否包含关键字

1、所需jar包

2、代码示例

import org.apache.poi.hwpf.HWPFDocument;  
import org.apache.poi.hwpf.extractor.WordExtractor;  
import org.apache.poi.xwpf.usermodel.XWPFDocument;  
import org.apache.poi.xwpf.usermodel.XWPFParagraph;  
  
import java.io.File;  
import java.io.FileInputStream;  
import java.io.IOException;  
import java.util.List;  
  
public class WordDocumentKeywordChecker {  
  
    public static void main(String[] args) {  
        String filePath = "path/to/your/document.docx"; // 可以是.doc或.docx  
        String keyword = "your_keyword";  
  
        try {  
            boolean containsKeyword = checkDocumentForKeyword(filePath, keyword);  
            System.out.println("Document contains keyword: " + containsKeyword);  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }  
  
    public static boolean checkDocumentForKeyword(String filePath, String keyword) throws IOException {  
        File file = new File(filePath);  
        String fileName = file.getName().toLowerCase();  
  
        if (fileName.endsWith(".doc")) {  
            return checkDocForKeyword(filePath, keyword);  
        } else if (fileName.endsWith(".docx")) {  
            return checkDocxForKeyword(filePath, keyword);  
        } else {  
            throw new IllegalArgumentException("文件类型不支持: " + fileName);  
        }  
    }  
  
    private static boolean checkDocForKeyword(String filePath, String keyword) throws IOException {  
        FileInputStream fis = new FileInputStream(filePath);  
        HWPFDocument document = new HWPFDocument(fis);  
        WordExtractor extractor = new WordExtractor(document);  
  
        String[] paragraphs = extractor.getParagraphText();  
        for (String paragraph : paragraphs) {  
            if (paragraph != null && paragraph.contains(keyword)) {  
                fis.close();   
				return true;  
            }  
        }  
  
        fis.close(); // 不要忘记关闭文件输入流  
        return false;  
    }  
  
    private static boolean checkDocxForKeyword(String filePath, String keyword) throws IOException {  
        FileInputStream fis = new FileInputStream(filePath);  
        XWPFDocument document = new XWPFDocument(fis);  
        List<XWPFParagraph> paragraphs = document.getParagraphs();  
  
        for (XWPFParagraph paragraph : paragraphs) {  
            String text = paragraph.getText();  
            if (text != null && text.contains(keyword)) {  
                fis.close();   
                return true;  
            }  
        }  
  
        fis.close(); // 如果没有找到关键字,也要确保关闭文件输入流  
        return false;  
    }  
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值