找不到我的空指针 - Java / Netbeans 8 中的递归



我试图写一个屏幕保护程序类型的程序,但我得到一个空指针异常,我无法跟踪。我正在查看一个目录,我认为正在发生的事情是,当"行走"到达一个文件夹而不是一个文件时,它会抛出异常。我就是不知道该怎么办!下面是代码:

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);
        }
}

}

这里是System out And error:

File:c:UsersGuyPicturesEditedGeographySnowdonFrom East (Capel Curig) 16-6-14 - No Cars.png
File:c:UsersGuyPicturesEditedGeographySnowdonFrom East (Capel Curig) 16-6-14.jpg
File:c:UsersGuyPicturesEditedGeographySnowdonFrom East (Capel Curig) 16-6-14.png
File:c:UsersGuyPicturesEditedGeographySnowdonIMG_7457.png
File:c:UsersGuyPicturesEditedGeographySnowdontest.png
Displaying image...c:UsersGuyPicturesEditedGeographySnowdontest.png
Displaying image...c:UsersGuyPicturesEditedGeographySnowdonIMG_7457.png
Displaying image...c:UsersGuyPicturesEditedGeographySnowdonIMG_7457.png
Displaying image...c:UsersGuyPicturesEditedGeographySnowdonFrom East (Capel Curig) 16-6-14.jpg
Displaying image...c:UsersGuyPicturesEditedGeographySnowdonFrom 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)

"显示图像....."来自Imagetime类。

这样做的结果是显示初始目录中的少数文件,但随后不再显示其他文件夹中的文件,因为异常将所有文件关闭。

其他一切都是按照我的预期工作,但我不知道如何消除这个问题。如果我移除

的walk
if(f.isDirectory()){
     walk(f.getAbsolutePath())
}

并保留if条件为空,则根本不会显示任何图像。

谁来帮帮我,这已经把我逼疯了太久了!

如果您的文件夹中有任何目录,那么您的数组长度将长于在数组末尾留下一组空条目的文件数量。当你的随机数碰到其中一个时,你会得到这个错误。我建议将你的数组转换为列表来消除这个问题。

相关内容

  • 没有找到相关文章

最新更新