publicstaticvoidmain(String[] args) { // Creates an array in which we will store the names of files and directories String[] pathnames;
// Creates a new File instance by converting the given pathname string // into an abstract pathname Filef=newFile("D:/Programming");
// Populates the array with names of files and directories pathnames = f.list();
// For each pathname in the pathnames array for (String pathname : pathnames) { // Print the names of files and directories System.out.println(pathname); } } }
// This filter will only include files ending with .py FilenameFilterfilter=newFilenameFilter() { @Override publicbooleanaccept(File f, String name) { return name.endsWith(".py"); } };
// This is how to apply the filter pathnames = f.list(filter);
// try-catch block to handle exceptions try { Filef=newFile("D:/Programming");
FilenameFilterfilter=newFilenameFilter() { @Override publicbooleanaccept(File f, String name) { // We want to find only .c files return name.endsWith(".c"); } };
// Note that this time we are using a File class as an array, // instead of String File[] files = f.listFiles(filter);
// Get the names of the files by using the .getName() method for (inti=0; i < files.length; i++) { System.out.println(files[i].getName()); } } catch (Exception e) { System.err.println(e.getMessage()); } } }
if (files != null && files.length > 0) { for (File file : files) { // Check if the file is a directory if (file.isDirectory()) { // We will not print the directory name, just use it as a new // starting point to list files from listDirectory(file.getAbsolutePath()); } else { // We can use .length() to get the file size System.out.println(file.getName() + " (size in bytes: " + file.length()+")"); } } } } publicstaticvoidmain(String[] args) { ListFilesRecursivelytest=newListFilesRecursively(); StringstartDir= ("D:/Programming"); test.listFiles(startDir); } }
输出:
1 2 3 4 5 6 7 8
Girl Talk - All Day.mp3 (size in bytes: 8017524) Celldweller - Frozen.mp3 (size in bytes: 12651325) Lim Taylor - Isn't It Wonderful.mp3 (size in bytes: 6352489) Radiohead - Everything in Its Right Place.mp3 (size in bytes: 170876098) minimax.c (size in bytes: 20662) super_hack.py (size in bytes: 114401) TODO.txt (size in bytes: 998)
D:\Programming\Coding Music\Radiohead - Everything in Its Right Place.mp3 D:\Programming\Coding Music\Lim Taylor - Isn't It Wonderful.mp3 D:\Programming\Coding Music\Celldweller - Frozen.mp3 D:\Programming\Coding Music\Girl Talk - All Day.mp3 D:\Programming\minimax.c D:\Programming\super_hack.py D:\Programming\TODO.txt