1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
/* List contents of a directory This Java example shows how list contents(files and sub-directories) of a directory using list method of Java File class. */ import java.io.*; public class ListContentOfDirectory { public static void main(String[] args) { //create file object File file = new File("C://FileIO"); /* * To list contents of a directory use, * String[] list() method of Java File class. * * This method returns an array of Strings containing name of files and * sub-directories. It reuturns an empty array, if directory is empty, * and null if file does not denotes a directory. */ String[] files = file.list(); System.out.println("Listing contents of " + file.getPath()); for(int i=0 ; i < files.length ; i++) { System.out.println(files[i]); } } } /* Output would be Listing contents of C:FileIO demo.txt HiddenDemo.txt JavaTemp10351.javatemp JavaTemp40534.javatemp ReadText.txt */ |
There is a mistake… it should be “file.length()” in the for loop