2016-04-06 25 views
1

我試圖將pdf文檔轉換爲文本,但即時獲取空指針異常..不明白爲什麼錯誤即將到來。該錯誤顯示在導入語句中。 林附加以下代碼:pdf到netbeans中使用pdfbox的文本蓋度8.1

public class PDFTextParser { 

    private static Object f; 

    public static void main(String args[]) { 
    PDFTextStripper pdfStripper = null; 
    PDDocument pdDoc = null; 
    COSDocument cosDoc = null; 

    File file = new File("D:\\1.pdf"); 
    try { 
     f = null; 
     PDFParser parser = new PDFParser((RandomAccessRead) f); 
     FileInputStream f= new FileInputStream(file); 
     parser.parse(); 
     cosDoc = parser.getDocument(); 
     pdfStripper = new PDFTextStripper(); 
     pdDoc = new PDDocument(cosDoc); 
     pdfStripper.setStartPage(1); 
     pdfStripper.setEndPage(5); 
     String parsedText = pdfStripper.getText(pdDoc); 
     System.out.println(parsedText); 
     } catch (IOException e) { 
     e.printStackTrace(); 
     } 
     } 
    } 


    This is the error im getting: 
    Exception in thread "main" java.lang.NullPointerException 
    at org.apache.pdfbox.pdfparser.PDFParser.<init>(PDFParser.java:138) 
    at org.apache.pdfbox.pdfparser.PDFParser.<init>(PDFParser.java:102) 
    at org.apache.pdfbox.pdfparser.PDFParser.<init>(PDFParser.java:61) 
    at PDFTextParser.main(PDFTextParser.java:33) 
+0

的可能的複製[?什麼是空指針異常,以及如何解決呢(http://stackoverflow.com/questions/218384 /什麼,是一個無效指針異常一nd-how-do-i-fix-it) – JEY

+0

程序中第33行的聲明是什麼? –

回答

1

是的,你是路過的空對象:

f = null; 
    PDFParser parser = new PDFParser((RandomAccessRead) f); 

順便說一句,作爲獎勵,這裏的一些更多的電流(和更短)的代碼來打開PDF與PDFBox的文件,我已經離開了異常處理:

File file = new File("D:\\1.pdf"); 
    PDDocument pdDoc = PDDocument.load(file); 
    pdfStripper = new PDFTextStripper(); 
    pdfStripper.setStartPage(1); 
    pdfStripper.setEndPage(5); 
    String parsedText = pdfStripper.getText(pdDoc); 
    System.out.println(parsedText); 
+0

非常感謝!它工作完美! – Ria