获取静态文件数组的长度?永远回来无效

时间:2013-02-12 21:21:16

标签: java arrays static processing

public PImage[] images;
public static File[] wallTiles = loadFolder("data/tiles/walls");
public static File[] floorTiles = loadFolder("data/tiles/floors");
public static int totalFiles = wallTiles.length+floorTiles.length;

private static File[] loadFolder(String string)
{
    File files = new File(string);

    File[] pngFiles = files.listFiles(new FilenameFilter()
    {
        public boolean accept(File directory, String fileName)
        {
            return fileName.endsWith(".png");
        };
    });
    return pngFiles;
}

第4行(其中分配了totalFiles)始终失败,因为wallTiles为null。我想在这个类(称为Art)中返回totalFiles,这样我就可以为我正在进行的游戏随机选择墙或地板纹理。谢谢收听。

2 个答案:

答案 0 :(得分:1)

来自API http://docs.oracle.com/javase/6/docs/api/java/io/File.html#listFiles()

...如果此抽象路径名不表示目录,则返回null ...

因此,检查目录是否存在以及是否有文件。

private static File[] loadFolder(String string)
{
    File files = new File(string);
    if(!files.exists() || !files.isDirectory()){
        System.out.println("Directory: "+string+" does not exists");       
        return new File[0];
    }

    File[] pngFiles = files.listFiles(new FilenameFilter()
    {
        public boolean accept(File directory, String fileName)
        {
            return fileName.endsWith(".png");
        };
    });
    return pngFiles;
}

答案 1 :(得分:0)

尝试使用目录的绝对路径,而不是相对

public static File [] wallTiles = loadFolder(“data / tiles / walls”);

- >

public static File [] wallTiles = loadFolder(“/ whatever_path / data / tiles / walls”);