This question already has answers here:
What is a NullPointerException, and how do I fix it?
                                
                                    (12个答案)
                                
                        
                2年前关闭。
            
        

我正在尝试编写Java程序来计算PDF文件的页数。但是,当我运行该程序时,出现错误,我不确定为什么。

这是错误:

Exception in thread "main" java.lang.NullPointerException at pdfpagecount.Pdfpagecount.main(Pdfpagecount.java:12)


这是产生错误的代码:

package pdfpagecount;

import java.io.File;
import java.io.FileInputStream;
import com.lowagie.text.pdf.PdfReader;

public class Pdfpagecount {

public static void main(String[] args) {
    File gopi = new File("C:\\Users\\Gopinath Muruti\\Desktop\\test.pdf");
    File listOfFile[] = gopi.listFiles();
    for(int i = 0; i < listOfFile.length; i++) {
        File tempFile = listOfFile[i];
        String fileName = tempFile.getName();
        System.out.println("File Name = " + fileName);
        try {
            if(fileName.toLowerCase().indexOf(".pdf") != -1) {
                PdfReader document = new PdfReader(new FileInputStream(new File("filename")));
                int noPages = document.getNumberOfPages();
                System.out.println("Number of Pages in the PDF document is = " + noPages);
            }
        }
        catch(Exception e) {
            System.out.println("Exception : " + e.getMessage());
            e.printStackTrace();
        }
    }
}
}

最佳答案

gopi.listFiles();返回null,因为gopi是文件,而不是目录或文件夹。所以你得到了NullPointerException
检查您的File对象是文件还是目录:

File file = new File(path);

boolean isDirectory = file.isDirectory(); // Check if it's a directory
boolean isFile =      file.isFile();      // Check if it's a regular file

07-28 01:22
查看更多