1. File类
文件和目录路径名的抽象表示形式,主要用于获取文件的相关属性以及创建文件或目录
。
1 2 3
| public class File extends Object implements Serializable, Comparable<File>
|
构造方法:没有无参构造。
1 2 3 4 5 6 7 8
| File(File parent, String child) 从父抽象路径名和子路径名字符串创建新的 File实例。 File(String pathname) 通过将给定的路径名字符串转换为抽象路径名来创建新的 File实例。 File(String parent, String child) 从父路径名字符串和子路径名字符串创建新的 File实例。 File(URI uri) 通过将给定的 file: URI转换为抽象路径名来创建新的 File实例。
|
常用方法:参考File类 jdk1.8 API
部分常用方法演示:
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
| public class TestFiles { public static void main(String[] args) throws IOException, Exception { File file = new File("files\\test\\target.txt"); System.out.println(file.canExecute()); System.out.println(file.canWrite()); System.out.println(file.canRead()); System.out.println(file.createNewFile()); System.out.println(file.delete()); Thread.sleep(2000); file.deleteOnExit(); System.out.println(file.exists()); System.out.println(file.getFreeSpace()/1024/1024/1024 + "GB"); System.out.println(file.getTotalSpace()/1024/1024/1024 + "GB"); System.out.println(file.getAbsolutePath()); System.out.println(file.getPath()); System.out.println(file.getName()); System.out.println(file.getParent()); System.out.println(file.isDirectory()); System.out.println(file.isFile()); System.out.println(file.isHidden()); System.out.println((System.currentTimeMillis()-file.lastModified()) / 1000 / 60); System.out.println(file.length()); file.mkdirs(); System.out.println(file); } }
|
2. FileFilter接口
FileFilter接口:实现按条件过滤指定文件
1 2 3 4
| public interface FileFilter { boolean accept(File pathname); }
|
- 当调用File类中的 listFiles() 方法时,支持传入 FileFilter 接口的实现类对象,对获取文件进行过滤,只有满足条件的文件才可出现在listFiles()的返回值中。——接口回调。
3. 统计指定类型文件
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
| public class TestShowAllFiles { static int fileCount = 0; public static void main(String[] args) { File file = new File("E:\\"); showAll(file); System.out.println("一共有 " + fileCount + " 个.class文件"); } public static void showAll(File dir) { File[] files = dir.listFiles( new FileFilter() { @Override public boolean accept(File pathname) { if (pathname.isDirectory()) { return true; } if (pathname.isFile()) { if (pathname.getName().endsWith(".class")) { return true; } } return false; } }); if (files != null) { for (File f : files) { if (f.isFile()) { System.out.println(f.getName()); fileCount++; } else { showAll(f); } } } } }
|