package com.awspaas.user.apps.gwgl.controller;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

public class WordUrlReaderUtil {

    // 下载网络文件
    public static byte[] downloadFile(String fileUrl) throws Exception {
        URL url = new URL(fileUrl);
        URLConnection conn = url.openConnection();
        conn.setRequestProperty("User-Agent", "Mozilla/5.0");
        conn.setConnectTimeout(10000);
        conn.setReadTimeout(10000);

        try (InputStream in = conn.getInputStream();
             ByteArrayOutputStream out = new ByteArrayOutputStream()) {

            byte[] buffer = new byte[4096];
            int len;
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            return out.toByteArray();
        }
    }

    // 【自动识别 doc / docx,不会报错】
    public static String getWordText(byte[] bytes) throws Exception {
        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);

        try {
            // 先尝试解析 docx
            XWPFDocument docx = new XWPFDocument(bais);
            XWPFWordExtractor extractor = new XWPFWordExtractor(docx);
            return extractor.getText();
        } catch (Exception e) {
            // 如果失败,再解析 doc
            bais = new ByteArrayInputStream(bytes);
            POIFSFileSystem fs = new POIFSFileSystem(bais);
            HWPFDocument doc = new HWPFDocument(fs);
            WordExtractor extractor = new WordExtractor(doc);
            return extractor.getText();
        }
    }

    // 测试
    public static void main(String[] args) {
        try {
            // 你的下载地址
            String url = "http://.doc"; // 可以是 doc 或 docx

            byte[] fileBytes = downloadFile(url);
            String content = getWordText(fileBytes);

            System.out.println("===== Word 内容 =====");
            System.out.println(content);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

更多推荐