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.

another NullPointerException problem with List interface

Thread view: 
Alan - 28 Dec 2007 03:18 GMT
Line 87 ("boolean addedOK = filelist.add(file);"), which is the add
method of the List interface, causes a NullPointerException, but I
cannot figure out why.

    The API says that add(element) can have this exception "if the
specified element is null and this list does not support null
elements".  However, the element (a File variable) is not null (it
prints out the filename).

    Can anyone tell me why I get this error?       Thanks, Alan

Output:

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

java.lang.NullPointerException
    at jat.util.file.AllFiles.listAllFiles(AllFiles.java:87)
    at jat.util.file.AllFiles.main(AllFiles.java:22)
file being added: URLget.java

----jGRASP: operation complete.

Code:

1 package jat.util.file;
 2
 3 import java.io.*;
 4 import java.io.FilenameFilter;
 5 import java.util.*;
 6
 7 public class AllFiles
 8 {
 9    /**   The main method is used for testing other methods
10          of the AllFiles class.
11    */
12    public static void main(String[] args)
13    {
14       File directory = new File(System.getProperty("user.dir"));
15       if (args.length > 0)
16       {
17          File tempFile = new File(args[0]);
18          if (tempFile.isDirectory()) { directory = tempFile; }
19       }
20       try
21       {
22          List<File> filelist = listAllFiles(directory, "java");
23          for (Iterator it = filelist.iterator(); it.hasNext();)
24          {
25             File file = (File) it.next();
26 //             System.out.println(file.getName());
27          }
28       }
29       catch (Exception  e)
30       {
31 //          System.err.println("Error in call to method
listAllFiles");
32       }
33    }
34
35    /**   The listAllFiles method provides a list of all files
36          found in the user-specified directory and its
37          subdirectories.
38
39          @param   dir         the directory at which the file
list
40                               should start
41          @param   extension   a string indicating the file
extension
42                               that should be used to filter the
results
43          @return  File[]      a list of File objects
44    */
45    public static List<File> listAllFiles(File dir, String
extension) throws Exception
46    {
47       try
48       {
49          if (!dir.isDirectory())
50          {
51             return null;         // Not a directory
52          }
53          else  // input file reference is a directory
54          {
55             // Initialize lists of files and directories
56             List<File> FileAndDirList = null;   // will contain
both
57             List<File> filelist = null;         // will contain
files only
58
59             // Get list of files in the input directory
60             FilenameFilter select = new FileListFilter(null,
extension, true);
61             File[] filearray = dir.listFiles(select);
62
63 //             for (int i = 0; i < filearray.length; i++)
64 //             {  System.out.println(filearray[i]); }
65
66             // If file array is not empty, convert it to a list
67             if (filearray.length > 0)
68             {
69                FileAndDirList = Arrays.asList(filearray);
70             }
71
72             // If there are files and/or directories, check
73             // to see if they are directories or other files
74             if (FileAndDirList != null)
75             {
76                for (Iterator<File> it =
FileAndDirList.iterator();
77                                              it.hasNext();)
78                {
79                   File file = it.next();
80                   // If this file is not a directory, add it to
81                   // the list of normal files
82                   if (!file.isDirectory())
83                   {
84                      System.out.println("file being added: "
85                                     + file.getName());
86
87                      boolean addedOK = filelist.add(file);
88                      System.out.println("addedOK = " + addedOK);
89                   }
90                   else { System.out.println("Directory: "
91                                     + file.getName());
92                   }
93                }
94                System.out.println("\n   filelist: \n" + filelist);
95             }
96
97             return null;         // crap crap crap crap crap
98          }
99       }
100       catch ( SecurityException  e )
101       {
102          e.printStackTrace();
103          return null;
104       }
105       catch ( RuntimeException  e )
106       {
107          e.printStackTrace();
108          return null;
109       }
110    }
111 }
112
113    /**   The FileListFilter class implements the
java.io.FilenameFilter
114          interface.
115    */
116    class FileListFilter implements FilenameFilter
117    {
118       private String name, extension;
119       private boolean includeDirectories;
120
121       public FileListFilter(String name, String extension,
122                               boolean includeDirectories)
123       {
124          this.name = name;
125          this.extension = extension;
126          this.includeDirectories = includeDirectories;
127       }
128
129       /**   The accept method determines whether or not a File
130             meets the filename filter criteria.
131
132             @param   name        a String indicating the filter
for
133                                  the filename; null means no
filter
134             @param   filename    a String that contains the
filename
135                                  of the file; null means no filter
136             @param   includeDirectories   a boolean value that
137                                           indicates whether or not
138                                           subdirectories should be
included
139                                           in the results
140             @return  boolean     indicates whether or not the file
141                                  meets the filtering criteria
142       */
143       public boolean accept(File directory, String filename)
144       {
145          boolean fileOK = true;
146
147          if (name != null)
148          { fileOK &= filename.startsWith(name); }
149
150          if (extension != null)
151          {
152             if (fileOK)
153             {
154                fileOK &= filename.endsWith('.' + extension);
155                if (!fileOK && includeDirectories)
156                {
157                   fileOK = (filename.indexOf('.') == -1);
158                }
159             }
160          }
161
162          return fileOK;
163       }
164    }
165
166
167
Owen Jacobson - 28 Dec 2007 03:30 GMT
> Line 87 ("boolean addedOK = filelist.add(file);"), which is the add
> method of the List interface, causes a NullPointerException, but I
[quoted text clipped - 6 lines]
>
>      Can anyone tell me why I get this error?       Thanks, Alan

>  57             List<File> filelist = null;         // will contain

...

>  87                      boolean addedOK = filelist.add(file);

In Java there is a difference between an empty list (a List object
with no elements) and no list at all (no List object).  The former is
a List and can be added to; the latter is not and will cause exactly
the error you encountered.

You probably want
 List<File> filelist = new ArrayList<File> ();
or some other concrete list type, on like 57, to create a new (empty)
list; what you've written is that filelist points to no list at all.

HTH,
-o
Alan - 28 Dec 2007 14:22 GMT
Owen,
     Thank you.  I am new to Java, and I had a misconception about
List.

   Sometimes I think I confuse the abstract class List with the List
Interface, too.

                             Alan
Lew - 28 Dec 2007 14:30 GMT
> Owen,
>       Thank you.  I am new to Java, and I had a misconception about
> List.
>
>     Sometimes I think I confuse the abstract class List with the List
> Interface, too.

Hard to do, since in the java.util package there is no abstract class "List".
 In fact, the only class "List" in the standard API is java.awt.List, which
is hard to imagine confusing with java.util.List, which it doesn't even
implement, and besides which java.awt.List is not abstract.

Signature

Lew

Alan - 28 Dec 2007 15:30 GMT
Lew,
     I put a lot of effort into developing misconceptions.

     Thanks, Alan


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.