Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / December 2007

Tip: Looking for answers? Try searching our database.

Null pointer exceptions

Thread view: 
Alan - 25 Dec 2007 16:30 GMT
I keep getting NullPointerExceptions in the code below.  I have
also provided the execution output below.  It seems when I add a check
on an error (such as I did at Line 56), I just get the exception at a
different spot.

     I am new to Java.  I think this has something to do with
conversions from an Array (of files from listfiles method of File
class) to a List, but I cannot pinpoint the problem.

     Is there something obviously wrong?

     My intent was to create a general utility method that returns a
list of files in the designated directory and its subdirectories.

                                   Thanks, Alan

----jGRASP exec: java jat.util.file.AllFiles

... Entering method listAllFiles ...
dir = My Java Code
java.lang.NullPointerException
    at jat.util.file.AllFiles.listAllFiles(AllFiles.java:56)
    at jat.util.file.AllFiles.listAllFiles(AllFiles.java:73)
FilenameFilter selected . . .
filelist contents:
null

Directory found
Children: (size = 48)
URLget.java

... Entering method listAllFiles ...
dir = URLget.java
FilenameFilter selected . . .
    at jat.util.file.AllFiles.main(AllFiles.java:22)
java.lang.NullPointerException
    at jat.util.file.AllFiles.listAllFiles(AllFiles.java:73)
    at jat.util.file.AllFiles.main(AllFiles.java:22)

----jGRASP: operation complete.

package jat.util.file;

import java.io.*;
import java.io.FilenameFilter;
import java.util.*;

public class AllFiles
{
/**    The main method is used for testing other methods
    of the AllFiles class.
*/
  public static void main(String[] args)
  {
     File directory = new File(System.getProperty("user.dir"));
     if (args.length > 0)
     {
        File tempFile = new File(args[0]);
        if (tempFile.isDirectory()) { directory = tempFile; }
     }
     try
        {
           List<File> filelist = listAllFiles(directory, "java");
           for (Iterator it = filelist.iterator(); it.hasNext();)
           {
    File file = (File) it.next();
    System.out.println(file.getName());
           }
        }
     catch (Exception  e)
     { }
}

/**    The listAllFiles method provides a list of all files
    found in the user-specified directory and its
    subdirectories.

    @param    dir   the directory at which the file list
              should start
    @param    extension    a string indicating the file
                               extension that should be used to
filter the
                               results
    @return    File[]        a list of File objects
*/
public static List<File> listAllFiles(File dir, String extension)
throws Exception
{
  System.out.println("\n\n... Entering method listAllFiles ...");
  try
  {
     List<File> contents = null;
     List<File> filelist = null;
     System.out.println("dir = " + dir.getName());
     FilenameFilter select = new FileListFilter(dir.getName(),
                                                       extension);
     System.out.println("FilenameFilter selected . . .");
     File[] filearray = dir.listFiles(select);
     if (filearray.length > 0)
      { filelist = Arrays.asList(filearray); }
     System.out.println("filelist contents:\n"
                                      + filelist + "\n");
     if (filelist != null)
     {
        System.out.println("filelist is NOT empty");
        contents = filelist;
     }

     if (dir.isDirectory())
     {
       System.out.println("Directory found");
       String[] children = dir.list();
       System.out.println("Children: (size = "                     + children.length
+ ")");
       for (int i = 0; i < children.length; i++)
       {
            System.out.println(children[i]);
            contents.addAll(listAllFiles(new File(dir,
                        children[i]), extension));
       }
  }
  return contents;
}
catch ( SecurityException  e )
{
   e.printStackTrace();
   return null;
}
catch ( RuntimeException  e )
{
   e.printStackTrace();
   return null;
}
}
}

/**    The FileListFilter class implements the
                java.io.FilenameFilter interface.
*/
class FileListFilter implements FilenameFilter
{
    private String name, extension;

    public FileListFilter(String name, String extension)
    {
       this.name = name;
       this.extension = extension;
    }

/**   The accept method determines whether or not a File
      meets the filename filter criteria.

     @param  directory  a <code>File</code> object that indicates
                                  the directory
     @param   filename   a String that contains the filename
            of the file
     @return   boolean      indicates whether or not the file
          meets the filtering criteria
*/
  public boolean accept(File directory, String filename)
  {
     boolean fileOK = true;
     if (name != null)
     { fileOK &= filename.startsWith(name); }

     if (extension != null)
     { fileOK &= filename.endsWith('.' + extension); }

     return fileOK;
  }
}
d0ngd0ng - 25 Dec 2007 16:43 GMT
public static List<File> listAllFiles(File dir, String extension)

You have to check if the parameter dir is a directior with
dir.isDirectory.

Because the invoking of the method listFiles on a no directory File
object  will return null.

>    I keep getting NullPointerExceptions in the code below.  I have
> also provided the execution output below.  It seems when I add a check
[quoted text clipped - 170 lines]
>
> }
Kira Yamato - 25 Dec 2007 19:53 GMT
>    I keep getting NullPointerExceptions in the code below.

NullPointerException is certainly java's version of C's dangling
pointer problem.

> [...]

Signature

-kira

Lew - 25 Dec 2007 20:22 GMT
>>    I keep getting NullPointerExceptions in the code below.
>
> NullPointerException is certainly java's version of C's dangling pointer
> problem.

Crude but effective analogy.  Note that the scope, causes and impact of the
two are not equivalent.  Analysis and remediation also differ markedly for the
two types of error.

Signature

Lew

Roedy Green - 28 Dec 2007 13:55 GMT
On Tue, 25 Dec 2007 08:30:21 -0800 (PST), Alan
<jalanthomas@verizon.net> wrote, quoted or indirectly quoted someone
who said :

>NullPointerExceptions
for generic help tracking these down see:

http://mindprod.com/jgloss/runerrormessages.html#NULLPOINTEREXCEPTION
Signature

Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.