0

I am trying to code a Java program to calculate the number of pages for PDF files. But when I run this program I get an error which I am not sure why.

This is the error:

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

Here is the code that produces the error:

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();
        }
    }
}
}
Andrew Thompson
  • 163,965
  • 36
  • 203
  • 405
  • Can you please share the error with us? – Bas de Groot Oct 23 '18 at 06:57
  • I am getting this error "Exception in thread "main" java.lang.NullPointerException at pdfpagecount.Pdfpagecount.main(Pdfpagecount.java:12)" Thank you. – Gopinath Muruti Oct 23 '18 at 07:00
  • 1
    Since this looks like a file as opposed to a directory.. `File gopi = new File("C:\\Users\\Gopinath Muruti\\Desktop\\test.pdf");` .. this line makes no sense .. `File listOfFile[] = gopi.listFiles();`. Read the [docs on `listFiles()`](https://docs.oracle.com/javase/9/docs/api/java/io/File.html#listFiles--) .. *"**Returns:** .. `null` if this abstract pathname does not denote a directory, .."* – Andrew Thompson Oct 23 '18 at 07:09

2 Answers2

2

gopi.listFiles(); returns null because gopi is a file, not a directory or folder. So you got NullPointerException. Check your File object is file or directory:

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
fuat
  • 993
  • 1
  • 12
  • 19
1

NPE meand that some oubject you tried to dereference was null - most probably it is

listOfFile[] = gopi.listFiles();

( which is by the way not the best way to to this. as you already have a file name )

I recommend to start reading tutorials on about how to read file in java.

Konstantin Pribluda
  • 12,042
  • 1
  • 26
  • 34