首先,讓我告訴你我到目前爲止的代碼:添加文件對象文件對象的數組
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;
}
目錄,文件和allDocs是類內聲明的任何方法之外的數組。
allDocs是我用來獲取感興趣的目錄HR中的每個目錄和文件的數組。我用allDocs = folder.listFiles();
我想讓文件成爲數組來存儲目錄HR中的所有文件,並且我希望目錄是將所有目錄存儲在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第一元素是文件。當第一個元素是一個目錄時,也會發生此問題。問題是文件[fileCount] =文件上的空指針異常;線,我不明白。 「文件」不爲空,我只是給它分配了一個值。當然文件[fileCount]在這種情況下爲空,但爲什麼如果我給它賦值呢?
文件聲明:
public class Methods
{
private static File[] files;
嘗試具體而不是打字太長。 :) – Batty
告訴你我想做什麼,爲什麼我不能做得不夠具體?我可以告訴你的不多。 – Lighthat
我的意思是,你告訴了一點額外:) – Batty