我试图编写一个屏幕保护程序类型的程序,但是我得到了一个我无法追踪的空指针异常。我正在浏览一个目录,我认为正在发生的事情就是“走路”。到达文件夹而不是文件,它会抛出异常。我无法解决这方面的问题!这是代码:
import java.io.File;
import java.io.IOException;
import java.util.Random;
public class Recursion {
public void walk(String path) throws InterruptedException, IOException {
File root = new File(path);
File[] list = root.listFiles();
String[] fileArray = new String[list.length];
int i = 0;
if (list == null) {
return;
}
for (File f : list) {
if (f.isDirectory()) {
walk(f.getAbsolutePath());
} else if (f.isFile()) {
String outPath = f.getAbsolutePath();
System.out.println("File:" + outPath);
fileArray[i] = outPath;
i++;
}
}
for (int j = 0; j < fileArray.length; j++) {//WILL NEED TO CONVERT TO SOME FORM OF WHILE LOOP LATER
Random randomGenerator = new Random();//Initiates random generator
int randomInt = randomGenerator.nextInt(fileArray.length);////Limits max random to length of folder array
String files = fileArray[randomInt];//Chooses a filename based on random number
Imagetime go = new Imagetime();
go.Show(files);
}
}
}
这是系统输出和错误:
File:c:\Users\Guy\Pictures\Edited\Geography\Snowdon\From East (Capel Curig) 16-6-14 - No Cars.png
File:c:\Users\Guy\Pictures\Edited\Geography\Snowdon\From East (Capel Curig) 16-6-14.jpg
File:c:\Users\Guy\Pictures\Edited\Geography\Snowdon\From East (Capel Curig) 16-6-14.png
File:c:\Users\Guy\Pictures\Edited\Geography\Snowdon\IMG_7457.png
File:c:\Users\Guy\Pictures\Edited\Geography\Snowdon\test.png
Displaying image...c:\Users\Guy\Pictures\Edited\Geography\Snowdon\test.png
Displaying image...c:\Users\Guy\Pictures\Edited\Geography\Snowdon\IMG_7457.png
Displaying image...c:\Users\Guy\Pictures\Edited\Geography\Snowdon\IMG_7457.png
Displaying image...c:\Users\Guy\Pictures\Edited\Geography\Snowdon\From East (Capel Curig) 16-6-14.jpg
Displaying image...c:\Users\Guy\Pictures\Edited\Geography\Snowdon\From East (Capel Curig) 16-6-14 - No Cars.png
Exception in thread "main" java.lang.NullPointerException
at screensaver.Imagetime.Show(Imagetime.java:40)
at screensaver.Recursion.walk(Recursion.java:49)
at screensaver.Recursion.walk(Recursion.java:31)
at screensaver.ScreenSaver.main(ScreenSaver.java:23)
Java Result: 1
BUILD SUCCESSFUL (total time: 12 seconds)
&#34;显示图像.....&#34;来自Imagetime类。
这样做的结果是显示了初始目录中的少数文件,但是其他文件夹中没有其他文件,因为异常会使所有文件都关闭。
其他所有内容都与我的预期完全一致,但我不知道如何解决此问题。如果我删除&#39; walk&#39;为了
if(f.isDirectory()){
walk(f.getAbsolutePath())
}
并将if条件保留为空,我根本没有显示任何图像。
有人请求帮助,这已经让我心理太久了!
提前致谢。
答案 0 :(得分:2)
如果您的文件夹中有任何目录,则您的数组长度将长于您在阵列末尾留下一组空条目的文件数。当您的随机数击中其中一个时,您将收到此错误。我建议将数组切换到列表以消除这种情况。