what I'm trying to do is: - Scan a directory - For each folder found add its name to an ArrayList - Bring this ArrayList to Main Class and print it.
Here's my ScanDirs Class:
import java.io.File;
import java.util.ArrayList;
public class ScanDirs {
private ArrayList<String> locations;
public void scan() {
File rootDir = new File("./src/data");
locations = new ArrayList<String>();
for (File f : rootDir.listFiles()) {
String fName = f.getName();
locations.add(fName);
}
}
public ArrayList<String> getScan(){
return locations;
}
}
And here's the Main Class:
import java.util.ArrayList;
public class Main {
private static ScanDirs scanObject;
public static void main(String[] args) {
scanObject = new ScanDirs();
ArrayList<String> list = scanObject.getScan();
System.out.println(list);
}
}
My output is: null Why is this happening? Thanks in advance
You haven't called scan()
method anywhere in your code. So, simply calling getScan()
will result in un-intialized locations value i.e. null
.
what you can do is simply call scan()
method before calling getScan()
method like:
scanObject = new ScanDirs();
scanObject.scan(); // calling scan method
ArrayList<String> list = scanObject.getScan();
System.out.println(list);