在java中读取.docx文件 [英] Reading .docx file in java

查看:142
本文介绍了在java中读取.docx文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用 java 读取一个文件,以下是代码:

I am trying to read one file in java, following is the code :

public void readFile(String fileName){
        try {
        BufferedReader reader= new BufferedReader(new FileReader(fileName)); 
        String line=null;
        while((line=reader.readLine()) != null ){
            System.out.println(line);
        }
        }catch (Exception ex){}
            }

它在 txt 文件的情况下工作正常.但是,对于 docx 文件,它会打印奇怪的字符.我如何在 Java 中读取 .docx 文件.

It is working fine in case of txt file. However in case of docx file, it is printing weird characters. How can i read .docx file in Java.

推荐答案

import java.io.File;
import java.io.FileInputStream;
import java.util.List;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
    public void readDocxFile() {
            try {
                File file = new File("C:/NetBeans Output/documentx.docx");
                FileInputStream fis = new FileInputStream(file.getAbsolutePath());

                XWPFDocument document = new XWPFDocument(fis);

                List<XWPFParagraph> paragraphs = document.getParagraphs();


                for (XWPFParagraph para : paragraphs) {
                    System.out.println(para.getText());
                }
                fis.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

这篇关于在java中读取.docx文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆