File dir = new File(“C:/Path/To/My/Directory”);
String dirPath = "g:/Music/English"; File dir = new File(dirPath); String[] files = dir.list(); if (files.length == 0) { System.out.println("The directory is empty"); } else { for (String aFile : files) { System.out.println(aFile); } }
This example uses String[] list() method to get names of files and directories just as Strings, and you can’t do anything further with the files/directories.
String dirPath = "g:/Music/English"; File dir = new File(dirPath); File[] files = dir.listFiles(); if (files.length == 0) { System.out.println("The directory is empty"); } else { for (File aFile : files) { System.out.println(aFile.getName() + " - " + aFile.length()); } }
This example uses File[] listFiles() method to retrieve an array of File objects, so you can do something more with an individual file or directory, such as getting absolute path or file size.
Suppose we want to list only MP3 files, create a local class that implements the interface FilenameFilter, and overrides the accept(File file, String name) method as follows:
FilenameFilter mp3Filter = new FilenameFilter() { public boolean accept(File file, String name) { if (name.endsWith(".mp3")) { // filters files whose extension is .mp3 return true; } else { return false; } } };
If the accept() method returns true, the file will be listed. Then call the method listFiles(FilenameFilter filter) as follows:
String dirPath = "g:/Music/English"; File dir = new File(dirPath); File[] files = dir.listFiles(mp3Filter); if (files.length == 0) { System.out.println("There is no MP3 files"); } else { for (File aFile : files) { System.out.println(aFile.getName() + " - " + aFile.length()); } }Note: as the name suggests, the FilenameFilter interface is for filtering file names only. If you want to filter other file’s properties such as size or modification time, use the method listFiles(FileFilter filter)
Suppose you want to list only the files whose size is greater than 3MB, create a local class that implements the interface FileFilter, and overrides the accept(File file) method as follows:
FileFilter sizeFilter = new FileFilter() { public boolean accept(File file) { if (file.isFile() && file.length() > 3*1024*1024) { // filters files whose size greater than 3MB return true; } else { return false; } } };
Then call the method listFiles(FileFilter filter) as follows:
String dirPath = "g:/Music/English"; File dir = new File(dirPath); File[] files = dir.listFiles(sizeFilter); if (files.length == 0) { System.out.println("There is no files bigger than 3MB"); } else { for (File aFile : files) { System.out.println(aFile.getName() + " - " + aFile.length()); } }You can download a Java program for these examples at the end of this article.