Java文件列表:使用for循环时的NPE

时间:2014-01-18 11:51:42

标签: java linux nullpointerexception filepath

我编写了简单的java代码来在Linux中显示文件列表,以便将它用于使用TCP的FTP程序(我将逐步使用所有功能)。谷歌搜索大约半小时后我发布了这个问题。

import java.io.*;
class FileList
{
public static void main(String args[])
{
String dirname="/home/vaibhav/Test";
File f1=new File(dirname);
String sl[]=f1.list();
System.out.print(f1.list()+"......."+sl.length+" files found.");
for(int i=0;i<sl.length;i++)
{ 
System.out.print(sl[i]+" ");
}      
}
}

输出:

vaibhav@vaibhav-VirtualBox:~/Java$ javac FileList.java
vaibhav@vaibhav-VirtualBox:~/Java$ java FileList
Exception in thread "main" java.lang.NullPointerException
    at FileList.main(FileList.java:10)

我的目录测试和Java内容:

vaibhav@vaibhav-VirtualBox:~$ cd /home/vaibhav/Test
vaibhav@vaibhav-VirtualBox:~/Test$ dir
1  2
vaibhav@vaibhav-VirtualBox:~/Test$ ls -al
total 8
drwxrwxrwx  2 vaibhav vaibhav 4096 Jan 18 15:04 .
drwxr-xr-x 25 vaibhav vaibhav 4096 Jan 18 16:50 ..
-rw-rw-rw-  1 vaibhav vaibhav    0 Jan 18 15:04 1
-rw-rw-rw-  1 vaibhav vaibhav    0 Jan 18 15:04 2
vaibhav@vaibhav-VirtualBox:~/Test$ cd
vaibhav@vaibhav-VirtualBox:~$ cd /home/vaibhav/Java
vaibhav@vaibhav-VirtualBox:~/Java$ ls -al
total 20
drwxr-xr-x  2 vaibhav vaibhav 4096 Jan 18 16:52 .
drwxr-xr-x 25 vaibhav vaibhav 4096 Jan 18 16:50 ..
-rw-r--r--  1 vaibhav vaibhav  990 Jan 18 16:52 FileList.class
-rw-r--r--  1 vaibhav vaibhav  477 Jan 18 16:52 FileList.java
-rw-r--r--  1 vaibhav vaibhav  487 Jan 18 16:52 FileList.java~

当我将String dirname更改为/ home / vaibhav / Java也是pwd时,程序执行得很好。

问题是什么? 谢谢。

1 个答案:

答案 0 :(得分:0)

最好试试这个:

File folder = new File("your/path");
File[] listOfFiles = folder.listFiles();

    for (int i = 0; i < listOfFiles.length; i++) {
      if (listOfFiles[i].isFile()) {
        System.out.println("File " + listOfFiles[i].getName());
      } else if (listOfFiles[i].isDirectory()) {
        System.out.println("Directory " + listOfFiles[i].getName());
      }
    }

希望这有助于你