我正在處理該程序以獲取目錄中的所有文件。出於某種原因,我得到了第16行的NullPointerException。我不知道爲什麼,因爲這是一個模板,似乎與我們的老師在課堂上工作。謝謝。用Java獲取目錄中的所有文件的程序
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();
}
}
}
我如何檢查呢?我只是說pathName.list()!= null? – Crystal 2010-07-30 06:21:58
是@Crystal,你應該測試一下。然後決定在發生這種情況時應採取的措施:報告錯誤,提示用戶輸入正確的目錄等。 – krock 2010-07-30 10:19:14