package file;
import java.io.*;
import java.io.File;
/**
*
* @author ASUS
* 功能:列出所有驱动器的文件及文件夹
*/
public class ListAllFiles { /**
* @param args the command line arguments
*
*/
void list(){
// File fp;
File[] driver=File.listRoots();
for(int i=0;i<driver.length;i++){
// File[] file=
System.out.println(driver[i]);
File sp=new File("c:");
try {
listfile(sp);
}catch(IOException e){
String message=e.getMessage();
System.out.println(e);
}
}
}
//递归列出文件及文件夹
void listfile(File fp) throws IOException
{
File[] file=fp.listFiles();
for(int j=0;j<file.length;j++){
if(file[j].isDirectory()){
System.out.println("|__"+file[j].toString());
listfile(file[j]);
}
else{
System.out.println("__"+file[j]);
}
}
}
public static void main(String[] args) {
// TODO code application logic here
ListAllFiles laf=new ListAllFiles();
laf.list();
}
}为什么说空指针异常呢?
void listfile(File fp) throws IOException
{
File[] file=fp.listFiles();
if(file != null){//判断下是不是空了...如果递归到空了不判断会抛空指针吧
for(int j=0;j<file.length;j++){
if(file[j].isDirectory()){
System.out.println("|__"+file[j].toString());
listfile(file[j]);
}
else{
System.out.println("__"+file[j]);
}
}
}
}
如果fp是个空文件夹,file就是个空数组,当然会有空指针了
我的压缩包里面不止一两样东西哦,那可是我学习和工作的所有资料,不管是学习还是工作都会需要。
http://download.csdn.net/user/yangtonghai
Exception in thread "main" java.lang.NullPointerException
at file.ListAllFiles.listfile(ListAllFiles.java:44)
at file.ListAllFiles.listfile(ListAllFiles.java:47)
at file.ListAllFiles.listfile(ListAllFiles.java:47)
at file.ListAllFiles.list(ListAllFiles.java:30)
at file.ListAllFiles.main(ListAllFiles.java:58)
Java Result: 1