How can I determine if a file is a PDF file?

后端 未结 13 916
暖寄归人
暖寄归人 2020-12-24 11:57

I am using PdfBox in Java to extract text from PDF files. Some of the input files provided are not valid and PDFTextStripper halts on these files. Is there a clean way to ch

13条回答
  •  轮回少年
    2020-12-24 12:17

    You have to try this....

    public boolean isPDF(File file){
        file = new File("Demo.pdf");
        Scanner input = new Scanner(new FileReader(file));
        while (input.hasNextLine()) {
            final String checkline = input.nextLine();
            if(checkline.contains("%PDF-")) { 
                // a match!
                return true;
            }  
        }
        return false;
    }
    

提交回复
热议问题