Reading .docx file in java

Addict picture Addict · May 22, 2013 · Viewed 43.1k times · Source

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){}
            }

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.

Answer

Raju Ahmed picture Raju Ahmed · Dec 31, 2015
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();
            }
        }