1
我已經在word文檔中寫了一個字符串。但是,當我打開文檔來獲取字符串並將其存儲在另一個文檔中時,它給了我例外。Apache poi word文檔空指針異常
這是我的代碼。
XWPFDocument document = new XWPFDocument();
XWPFParagraph paragraphOne = document.createParagraph();
XWPFRun paragraphOneRunOne = paragraphOne.createRun();
paragraphOneRunOne.setBold(true);
paragraphOneRunOne.setItalic(true);
paragraphOneRunOne.setText("Hello world! This is paragraph one!");
paragraphOneRunOne.addBreak();
FileOutputStream outStream = null;
try {
outStream = new FileOutputStream("MyDov.docx");
document.write(outStream);
outStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try{
FileInputStream is = new FileInputStream(new File("MyDov.docx"));
XWPFDocument doc = new XWPFDocument(is); //Document with words
XWPFWordExtractor ex = new XWPFWordExtractor(doc); //To get the words
String words = ex.getText();
XWPFDocument newDoc = new XWPFDocument(); //Doc to write new doc to
XWPFParagraph para = newDoc.createParagraph(); //Paragraph
XWPFRun run = para.createRun();
run.setText(words);
}
newDoc.write(new FileOutputStream(new File("mydoc.docx")));}
catch (IOException e)
{System.out.println(e);}
它給了我這個例外。
Exception in thread "main" java.lang.NullPointerException
at org.apache.poi.xwpf.extractor.XWPFWordExtractor.extractHeaders(XWPFWordExtractor.java:162)
at org.apache.poi.xwpf.extractor.XWPFWordExtractor.getText(XWPFWordExtractor.java:87)
at atestpack.CreateDocumentFromScratch.main(CreateDocumentFromScratch.java:56)
How can I solve this exception?
您正在編寫您的文檔,然後立即閱讀它。您是否嘗試檢查該文件是否正常?您是否嘗試用MS word兼容的應用程序打開它?您是否嘗試閱讀* other *,絕對有效的單詞文檔? – AlexR
是這個文件還行有一句寫着Hello world的句子!這是第一段!我用寫字板打開了它。我已閱讀通過代碼創建我的其他文檔。 – Sarah
因此,請附上POI的來源,並嘗試通過調試器瀏覽堆棧。堆棧跟蹤不太深,你會很容易看到爲什麼NPE被拋出。 – AlexR