-2

I have created a dirctory named test. Within this directory I have created a file named test.txt. When I execute the program below, the output for list method on cmd does not show the list of files in test directory.

Following is my code:

import java.io.*;

public class f1{
    public static void main(String args[]){
    try{
        File f = new File("test");
                System.out.println(f.exists());
                System.out.println(f.isDirectory());
                System.out.println(f.isFile());
                System.out.println(f.list());
    }
    catch(Exception e){

    }
}

}

Following is the output:

 true
 true
 false
 [Ljava.io.File;@15db9742
user3382203
  • 169
  • 1
  • 6
  • 25
  • 6
    It's an array of Strings, you need to iterate over it and print the elements separately. Check this question: http://stackoverflow.com/questions/409784/whats-the-simplest-way-to-print-an-array – NeplatnyUdaj Mar 05 '15 at 13:40

4 Answers4

5

file.list() returns a String[]. Since arrays don't have an implementation of toString() (which is called when using println), it uses the default implementation of Object, which returns ClassName@hashCode. To convert an array to a String, you can use the java.util.Arrays class.

import java.util.Arrays;
// ...
System.out.println(Arrays.toString(file.list()));
Clashsoft
  • 11,553
  • 5
  • 40
  • 79
1

You cannot print arrays directly. File.list() returns an array of Strings. There's a utility class Arrays which will allow you to print it without iterating over it manually:

Arrays.toString(f.list())
NeplatnyUdaj
  • 6,052
  • 6
  • 43
  • 76
1

file.list()

Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname.

Java Docs

singhakash
  • 7,891
  • 6
  • 31
  • 65
-2

list returns a string array.

so if you specify a correct file URI then it should work.

import java.io.*;

public class f1
{
    public static void main(String args[]){
        try
        {
            File f = new File("test");
                    System.out.println(f.exists());
                    System.out.println(f.isDirectory());
                    System.out.println(f.isFile());
                    System.out.println(f.list());


                    for (int i = 0; i < f.list().length; i++)
                    {
                        System.out.println(f.list()[i]);
                    }
        }
        catch(Exception e){

        }
    }
}
Blaatz0r
  • 1,205
  • 1
  • 12
  • 24