毕向东_Java基础视频教程第20天_IO流(5~6)
第20天-05-IO流(文件列表一)
String[] list()
Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname.
String[] list(FilenameFilter filter)
Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter.
File[] listFiles()
Returns an array of abstract pathnames denoting the files in the directory denoted by this abstract pathname.
File[] listFiles(FileFilter filter)
Returns an array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter.
File[] listFiles(FilenameFilter filter)
Returns an array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter.
package bxd; import java.io.File; public class FileDemo4 { public static void method_1() { File[] files = File.listRoots(); for (File file : files) { System.out.println(file); } } public static void method_2() { File dir = new File("/Users/Eric/Desktop"); // 如果File dir传入的不是目录而是文件, 则会抛出空指针异常 for (String name : dir.list()) { System.out.println(name); } } public static void main(String[] args) { method_2(); } }
第20天-06-IO流(文件列表二)
package bxd; import java.io.File; import java.io.FilenameFilter; public class FileDemo5 { public static void method_1() { File demoDir = new File("/Users/Eric/Desktop"); String[] names = demoDir.list(new FilenameFilter() { @Override public boolean accept(File dir, String name) { // accept方法的入参File dir即为File demoDir return name.endsWith(".pdf"); } }); for (String name : names) { System.out.println(name); } } public static void method_2() { File dir = new File("/Users/Eric/Desktop"); for (File file : dir.listFiles()) { System.out.println(file.getName() + "::" + file.length()); } } public static void main(String[] args) { method_2(); } }