1、我们已经写过File的相关代码:
BufferedReader bf = new BufferedReader(new FileReader(new File("aa.txt")));
2、其实FIle这个类自身也是非常强大的,封装了很多操作文件/目录的方法,今天我们就需要去详细的学习这个类!
3、概述: java.io.File 类是文件和目录路径名的抽象表示,主要用于文件和目录的创建、查找和删除等操作。
4、构造方法:
构造方法 | 备注 |
---|---|
public File(String path) | 通过将给定的路径名字符串转换为抽象路径名来创建新的 File实例。 |
public File(String parent, String child) | 从父路径名字符串和子路径名字符串创建新的 File实例。 |
public File(File parent, String child) | 从父抽象路径名和子路径名字符串创建新的 File实例。 |
5、案例:
// 文件路径名
String pathname2 = "D:\\aaa\\bbb.txt";
File file2 = new File(pathname2);
// 通过父路径和子路径字符串
String parent = "d:\\aaa";
String child = "bbb.txt";
File file3 = new File(parent, child);
// 通过父级File对象和子路径字符串
File parentDir = new File("d:\\aaa");
String child = "bbb.txt";
File file4 = new File(parentDir, child);
6、常用方法:
常用方法 | 备注 |
---|---|
public String getAbsolutePath() | 返回此File的绝对路径名字符串。 |
public String getPath() | 将此File转换为路径名字符串。 |
public String getName() | 返回由此File表示的文件或目录的名称。 |
public long length() | 返回由此File表示的文件的长度。 |
7、案例:
public class FileGet {
public static void main(String[] args) {
File f = new File("d:/a/b.java");
System.out.println("文件绝对路径:"+f.getAbsolutePath());
System.out.println("文件构造路径:"+f.getPath());
System.out.println("文件名称:"+f.getName());
System.out.println("文件长度:"+f.length()+"字节");
File f2 = new File("d:/aaa");
System.out.println("目录绝对路径:"+f2.getAbsolutePath());
System.out.println("目录构造路径:"+f2.getPath());
System.out.println("目录名称:"+f2.getName());
System.out.println("目录长度:"+f2.length());
}
}
我们会发现一个问题,当文件被移动后,那么这段代码就不再能获得这个File对象,所以这个地方路径不够灵活
本电子书目录:《Java基础的重点知识点全集》