Hey everyone,
I was attempting to get the lastmodified file from a folder, and to do so I used File.listFiles() method which is returning a null pointer exception even though the folder is not empty.

I had this piece of code working about two days ago and I am not sure what changed since. I have looking java docs and I have realized that File.listFiles() will return a null if the arbitrary path is not found. But in this case the path does exists and as I mentioned it did work two days ago.

The for loop (has comment besides it) is the one that returns NPE.

Any hints or even any alternate methonds are appreciated.

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;

/*------------------ util imports ------------------------------*/
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;

/*------------------- SAX Parser Imports ------------------ */
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.SAXParser;
import org.xml.sax.SAXException;
import org.xml.sax.Attributes;

public class ReadXMLFile extends DefaultHandler
    private String temp = " ";
    Transaction transaction = new Transaction();

      void ReadErrorFile() throws IOException, SAXException, ParserConfigurationException
            SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm;ss");

             String directory = "C: / Users //hbhasin/Documents/Error/";
             File ErrorFile = new File(directory);
            String Er_FileName = " ";

            long LastModifiedFile = Long.MIN_VALUE;
            File choice = null;

             File[] files= ErrorFile.listFiles(new FileFilter()
                 public boolean accept(File file)
                   return file.isFile();

             for(File file : files) //this for loop returns NPE
                  if(file.lastModified() > LastModifiedFile)
                      choice = file;
                      LastModifiedFile = file.lastModified();
                      Er_FileName = file.getName();

Recommended Answers

All 3 Replies

I have figured out. Still not sure why its doing what its doing. Once I do figure out that I will post a solution as a reference for others.

Have you tried getting the name or doing anything else with the initial file to see if it works correctly?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.