首先,让我展示一下我目前拥有的代码:
public void populateArray(){
//NOTE: THIS METHOD SHOULD BE RUN FIRST. Many of the methods in this class rely on a populated file array to function.
// This method will populate our file array.
// First, we note the directory we want to pull files from.
File folder = new File("HR");
File dir = new File("");
File file = new File("");
//Then we fill an array with the list of documents in that directory
//This will also include folders.
int count = 0;
allDocs = folder.listFiles();
int fileCount = 0;
int dirCount = 0;
System.out.println("Displaying contents of directory...");
while (count < allDocs.length){
System.out.println("Found: " + allDocs[count]);
count++;
}
System.out.println("Sorting directories and files separately...");
count = 0;
while (count < allDocs.length){
if (allDocs[count].isDirectory()){
dir = new File(allDocs[count].getPath());
dirs[dirCount] = dir;
System.out.println("Document " + allDocs[count].getPath() + " sorted into -Directory- array at position " + dirCount);
dirCount++;
}
else{
file = new File(allDocs[count].getPath());
files[fileCount] = file;
System.out.println("Document " + allDocs[count].getPath() + " sorted into -File- array at position " + fileCount);
fileCount++;
}
count++;
}
return;
}
files、dirs和allDocs是类中在任何方法之外声明的数组。
allDocs是我用来获取感兴趣目录HR中的每个目录和文件的数组。我使用allDocs = folder.listFiles(); 来实现这一点。
我想让files成为存储目录HR中所有文件的数组,而将dirs作为存储HR中所有目录的数组,但我不想存储HR目录中任何内容的目录。
我尝试通过println "Sorting directories and files separately." 下的循环来实现此目标。
问题出在这里:
else{
file = new File(allDocs[count].getPath());
files[fileCount] = file;
System.out.println("Document " + allDocs[count].getPath() + " sorted into -File- array at position " + fileCount);
fileCount++;
}
这里出现问题是因为allDocs中的第一个元素是文件。当第一个元素是目录时,问题也会出现。问题在于文件files[fileCount] = file;行产生了空指针异常,我不明白原因。虽然“file”不为空,但我仍然赋予它一个值。当然,在这种情况下,files[fileCount]为空,但如果我给它赋值,那么这有什么关系呢?
文件声明:
public class Methods
{
private static File[] files;
List<File>
而不是数组?这会使所有的事情变得更简单...但听起来是files
为空,而不是file
。 - Jon Skeetfiles
变量似乎没有被初始化,因此导致了NPE。 - wypieprz