java.io.File #listFiles() Returns null from Window

2019-08-01 10:28发布

I have created this following method which I execute from a main thread

public static LinkedList<File> checkFile(String path, LinkedList<File> result) Throws IOException, SecurityException{
    File root = new File(path);
    File[] list = root.listFiles();

    if (list == null)
        return result;

    for (File f : list) {
        if (f.isDirectory()) {
            checkFile(f.getAbsolutePath(), result);
        } else {
                result.add(f.getAbsoluteFile());
        }
    }
    return result;
}

As long as it looks into the same location as the file itself, it can list all the files. But as soon as I point it to some other location (e.g. C:\somedir) it always returns null. When I run this inside eclipse, it is working fine. I don't assume that it's an issue with the classpath since I have added JAVA_HOME in windows path so it gets picked up (and the javac command also works fine).

I remember that there was a java bug in version 1.4 which was based around the error handling of listFiles method execution. But I am not sure why this is not working when I run it from command line using java command.

you can use the following wrapper to run it

public static void main(String[] args) throws IOException {

    if (args.length == 0 || args[0] == null){
        System.out.println("please specify path to the project's work folder");
        return;
    }

    String folderPath = (String) args[0];
    LinkedList<File> result = new LinkedList<>();

    result = checkFile(folderPath, result);
    long startTime = System.currentTimeMillis();
    for (File file : result) {
        System.out.println(file.getName());
    }

}

EDIT

Okay, I have realised that I used a literal "path" instead of the parameter path and thanks for everyone who pointed this out. But the main problem prevails. The path is not recognised if it is not in the location as the executable class itself. When I try to run this from Eclipse, as a project, it works! But when I try to do it from command prompt using simple command, It doesn't work and #listFiles() always returns null.

java SomeExecItem -C:\myFolder\withclasses

From java.io.File#listFiles() method source analysis, What I understand is that if isInvalid() is evaluated as false when I run it from command line. The only possible reason is that the indexOf('\u0000') is evaluated as -1?

What is the difference here? Since I am not running in admin mode, I suppose Eclipse's view/read permission should be the same as a standalone command line application in cmd prompt?

标签: java java-io
2条回答
萌系小妹纸
2楼-- · 2019-08-01 11:00

Change File root = new File("path"); to File root = new File(path);. This will fix the problem.

查看更多
Deceive 欺骗
3楼-- · 2019-08-01 11:20

You are not passing the parameter correctly. The try java SomeExecItem "C:\myFolder\withclasses" or java SomeExecItem C:\myFolder\withclasses.

查看更多
登录 后发表回答