0

I am having issues with various exceptions in my code. The class is designed to find all folders/subfolders on the computer and list them as an ArrayList. It does not care about the files in them. Here is the code. please help, I have been frustrated with this for a week now.

import java.io.File;
import java.util.ArrayList;


public class Detector
{
   private ArrayList<String> paths;

   public Detector()
   {
      File[] roots = File.listRoots();
      for(File drive : roots)
      {
         getPaths(drive.listFiles());
      }
   }
   public Detector(String str)
   {

      File[] bob = new File(str).listFiles();
      getPaths(bob);
   }

   public void getPaths(File[] files)
   {
      for (File file : files)
      {
          if(file.isDirectory())
          {
             paths.add(file.getName());
             getPaths(file.listFiles());
          }
      }
   }

   public ArrayList<String> getPathList()
   {
      return paths;
   }

   public void printPaths()
   {
      for(String str: this.getPathList())
      {
         System.out.println(str);
      }
   }
   public static void main(String[] args)
   {
         Detector tom = new Detector("/F:");
         tom.printPaths();
   }
}
arshajii
  • 127,459
  • 24
  • 238
  • 287

3 Answers3

2

You never initialized paths:

private ArrayList<String> paths = new ArrayList<String>();

Note that I've also used a type parameter of String here, as you should. In general try to stay away from using raw types.

arshajii
  • 127,459
  • 24
  • 238
  • 287
1

You have incorrect syntax at this line

private ArrayList<String> paths;

You are not initializing arraylist properly. in order to initialize it properly you would have to do

private ArrayList<String> paths = new ArrayList<>();

Note: I did not put String inside <> as its redundant in java 1.7.

Maciej Cygan
  • 5,351
  • 5
  • 38
  • 72
0

Additional remark:

File.listFiles() might return null which might be your NullPointerException. So do:

public void getPaths(File[] files)
{
    if (files == null) {
        return;
    }

And Java 7 has a Files.walkFileTree which comes with a couple of new classes, but is worth getting accustomed to.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138