gpt4 book ai didi

java - NPE 关于阅读 PDF 页数的程序

转载 作者:行者123 更新时间:2023-12-01 19:46:48 24 4
gpt4 key购买 nike

我正在尝试编写一个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

关于java - NPE 关于阅读 PDF 页数的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52942910/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com