user974047
user974047

Reputation: 2285

Opening directories in Java

I would like to be able to open up directories using Java code, directory meaning a "folder" that contains a folder, which in turn contains files. This is the part of the code that I have now:

public void listFiles(String folder) {
    File directory = new File(folder);
    File[] contents = directory.listFiles();
    System.out.println(contents);

For some reason, if I point the folder to the directory level, it returns this line:

   [Ljava.io.File;@67d07b41

But if I point it one level down (at the folder level, which directly contains the files) then it will list out the file names in the folder just fine. Can someone give me pointers as to why this is not working for me?

Upvotes: 6

Views: 28752

Answers (1)

Maurício Linhares
Maurício Linhares

Reputation: 40333

Change your code to:

public void listFiles(String folder){
File directory = new File(folder);
File[] contents = directory.listFiles();
for ( File f : contents) {
  System.out.println(f.getAbsolutePath());
}

And you will see all full paths printed.

You're getting that weird output because you are printing an array object and that's what array objects will have as a toString(). If you want to print the contents of the array you have to do it manually as above.

Upvotes: 7

Related Questions