【发布时间】:2014-03-17 00:44:23
【问题描述】:
首先,让我向您展示我目前拥有的代码:
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 中所有目录的数组,但我不想存储任何内容人力资源部的董事。
我尝试使用 println“分别对目录和文件进行排序”下的循环来执行此操作。
问题出在这里:
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; 上的空指针异常。线,我不明白。 “文件”不为空,我只是为它分配了一个值。当然,在这种情况下 files[fileCount] 为 null,但如果我为它分配一个值,这有什么关系呢?
文件声明:
public class Methods
{
private static File[] files;
【问题讨论】:
-
尽量具体,不要输入太长。 :)
-
有什么理由不能使用
List<File>代替数组?它会让所有这一切变得更简单......但听起来它是空的files,而不是file。 -
从上面的代码可以看出
files变量没有被初始化,从而导致NPE。 -
由于您的问题与
files变量直接相关,因此查看它的声明会非常有帮助。 -
如果它为空,那么您没有将值放入其中。您将值放入不存在的数组中。您必须先创建数组,然后才能为其索引赋值。