-1

This is a sorting algorithm test file. I am getting NullPointer error:

"Exception in thread "main" java.lang.NullPointerException
    at Test.loadFiles(Test.java:28)
    at Test.main(Test.java:39)"

The problem seems to be with "filecache[x].setName(nameOffiles[x]);" Please guide. Thanks.

import java.io.File;
public class Test {
   static File folder = new File("D:\\");
   static File[] listOfFiles = folder.listFiles();
   static String[] nameOffiles = new String[30];
   static long[] sizeOffiles = new long[30];
   static int i = 0;
   static MyFile filecache[] = new MyFile[30];
   public static void readFiles(){
      for (File file : listOfFiles) {
         if (file.isFile()) {
            nameOffiles[i] = file.getName();
            sizeOffiles[i] = file.length();
            i++;
         }
       }
       i = 0;
   }
   public static void loadFiles(){
      for(int x = 0; x <nameOffiles.length; x++){
         filecache[x].setName(nameOffiles[x]);
         filecache[x].setSize(sizeOffiles[x]);
      }
   }
   public static void testFiles(){
      Sorting sort1 = new Sorting();
      sort1.quickSort(filecache);
   }
   public static void main(String[] args) {
      readFiles();  
      loadFiles();
      testFiles();
      for(int x = 0; x < filecache.length; x++){
         System.out.println(filecache[x]);
      }
   }
}
M. A. Kishawy
  • 5,001
  • 11
  • 47
  • 72
Haris
  • 11
  • 1

2 Answers2

2

You're not initializing the objects in your filecache array, hence the NullPointerException. Try like this:

public static void loadFiles() {
    for(int x = 0; x < nameOffiles.length; x++){
        MyFile myFile = new MyFile();
        myFile.setName(nameOffiles[x]);
        myFile.setSize(sizeOffiles[x]);

        filecache[x] = myFile;
    }
}

Also, if you have more than 30 files, readFiles will throw an ArrayIndexOutOfBoundsException. Either initialize your arrays to have the same length as the number of files, or use collection types instead of arrays (preferred).

Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156
0

Your filecache array may have been created with a size of 30, but each element in the array is null until you put something in it. So, filecache[0].setName() will throw a null pointer exception.

Make sure you add a new MyFile object at the required index in the array before trying to call methods on it.

for(int x = 0; x <nameOffiles.length; x++){
    if(filecache[x] == null) {
        filecache[x] = new MyFile();
    }
    filecache[x].setName(nameOffiles[x]);
    filecache[x].setSize(sizeOffiles[x]);
}
Jason
  • 11,744
  • 3
  • 42
  • 46