Pracuję nad tym programem, aby uzyskać wszystkie pliki w katalogu. Z jakiegoś powodu otrzymuję NullPointerException na linii 16. Nie wiem dlaczego, ponieważ jest to szablon, który wydawał się działać w klasie z naszym nauczycielem. Dzięki.Program do pobierania wszystkich plików w katalogu w Javie
import java.util.*;
import java.io.*;
public class FindDirectories {
public static void main(String[] args) {
if (args.length == 0) {
args = new String[] { ".." };
}
List<String> nextDir = new ArrayList<String>();
nextDir.add(args[0]); // either the one file, or the directory
try {
while(nextDir.size() > 0) { // size() is num of elements in List
File pathName = new File(nextDir.get(0)); // gets the element at the index of the List
String[] fileNames = pathName.list(); // lists all files in the directory
for(int i = 0; i < fileNames.length; i++) {
File f = new File(pathName.getPath(), fileNames[i]); // getPath converts abstract path to path in String,
// constructor creates new File object with fileName name
if (f.isDirectory()) {
System.out.println(f.getCanonicalPath());
nextDir.add(f.getPath());
}
else {
System.out.println(f);
}
}
nextDir.remove(0);
}
}
catch(IOException e) {
e.printStackTrace();
}
}
}
jak mogę to sprawdzić? Czy mogę po prostu powiedzieć pathName.list()! = null? – Crystal
Tak @ Crystal, powinieneś to sprawdzić. Następnie zdecyduj, co zrobić, gdy to się stanie: zgłoś błąd, zapytaj użytkownika o poprawny katalog itp. – krock