Question

I did this simple experiment to list all files/directory in a parent directory. Did this by making a java project in eclipse by name 'JavaProject' and a class 'Temp.java' under src/com. Code is as below:

 public class Temp {
public static void main(String[] args) {

    search("../JavaProject");
}

public static void search(String dName) {
    String[] files = new String[100];
    File search = new File(dName); // make file object
    if (!search.isDirectory()) {
        return;
    }
    files = search.list(); // create the list
    for (String fn : files) {// iterate through it
        System.out.print("  " + fn);
        File temp = new File(fn);
        if (temp.isDirectory()) {
            search(fn);
        }
        System.out.println();
        }
    }
} 

The file structure is as below :

  • JavaProject(dir)

    • .classpath(file)

    • .project(file)

    • .settings(dir)

      • org.eclipse.jdt.core.prefs(file)
    • bin(dir)

      • com(file)

        • Temp.class(file)
    • src(dir)

      • com(dir)

        • Temp.java(file)

When I run the above program, it gives the following output:

 .classpath

 .project

 .settings  org.eclipse.jdt.core.prefs

  bin  com

  src  com

I cant understand why it does not print the .java file and .class file inside the com folders. When I try debugging then the file object on 'com' returns 'false' for both isDirectory() and isFile() methods.

Était-ce utile?

La solution 2

You can use listFiles() instead of list(). See below example:

public class Program {

    public static void main(String args[]) throws IOException {
        search(new File("."), 0);
    }

    public static void search(File file, int level) {
        if (!file.isDirectory()) {
            return;
        }

        for (File f : file.listFiles()) {
            for (int i = 0; i < level; i++) {
                System.out.print("    ");
            }
            System.out.println(f.getName());
            if (f.isDirectory()) {
                search(f, ++level);
            }
        }
    }
}

Autres conseils

When it gets to the 'com' directory your code is doing:

File temp = new File("com");

Since you have not specified any path this will be taken to be relative to the current directory which is not the directory containing 'com'.

You should use something like:

File temp = new File(parent, fn);

where parent is the File object for the parent directory.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top