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();
}
}
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 .
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.