目录
1. File类
1.2 基本概念
-- java.io.File
类主要用于描述文件或目录路径的抽象表示信息,可以获取文件或目录的特征信息,如:大小等。
1.3 常用的方法 :(文件的操作)
方法声明 | 功能介绍 |
---|---|
File(String pathname) | 根据参数指定的路径名来构造对象 |
File(String parent, String child) | 根据参数指定的父路径和子路径信息构造对象 |
File(File parent, String child) | 根据参数指定的父抽象路径和子路径信息构造对象 |
boolean exists() | 测试此抽象路径名表示的文件或目录是否存在 |
String getName() | 用于获取文件的名称 |
long length() | 返回由此抽象路径名表示的文件的长度 |
long lastModified() | 用于获取文件的最后一次修改时间 |
String getAbsolutePath() | 用于获取绝对路径信息 |
boolean delete() | 用于删除文件,当删除目录时要求是空目录 |
boolean createNewFile() | 用于创建新的空文件 |
代码示例:
public class FileTest01 {
public static void main(String[] args) throws IOException {
// 1.构造File类型的对象与E:/a.txt文件关联
File f1 = new File("E:/a.txt");
// 2.若文件存在则获取文件的相关特征信息并打印后删除文件
if(f1.exists()){
System.out.println("文件的名称是:" + f1.getName());
System.out.println("文件的大小是:" + f1.length());
Date date = new Date(f1.lastModified());
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
String format1 = format.format(date);
System.out.println("文件最后一次修改的时间为:" + format1);
// 绝对路径: 主要指以根目录开始的路径信息,如:c:/ d:/ /..
// 相对路径: 主要指以当前目录所在位置开始的路径信息,如:./ ../ 相对路径
System.out.println("文件的绝对路径信息:"+f1.getAbsolutePath());
System.out.println(f1.delete()?"文件删除成功!":"文件删除失败!");
}else {
// 3.若文件不存在则创建新的空文件
System.out.println(f1.createNewFile()?"文件创建成功!":"文件创建失败!");
}
}
}
1.4 常用的方法 :(目录的操作)
方法声明 | 功能介绍 |
---|---|
boolean mkdir() | 用于创建目录 |
boolean mkdirs() | 用于创建多级目录 |
File[] listFiles() | 获取该目录下的所有内容 |
boolean isFile() | 判断是否为文件 |
boolean isDirectory() | 判断是否为目录 |
File[] listFiles(FileFilter filter) | 获取目录下满足筛选器的所有内容 |
案例:
实现指定目录以及子目录中所有内容的打印。(例如:目录层级为:D:/一级目录/二级目录/三级目录/a.txt)
public class FileTest {
// 实现指定目录以及子目录中所有内容的打印
public static void show(File file) {
// 获取目录下的所有内容并记录到一维数组中
File[] filesArray = file.listFiles();
// 遍历数组
for (File tf: filesArray) {
String name = tf.getName();
// 判断是否为文件,若是则直接打印文件名称
if (tf.isFile()) {
System.out.println(name);
}
// 若是目录,则使用[]将目录名称括起来
if (tf.isDirectory()) {
System.out.println("[" + name + "]");
show(tf); // 使用递归的思想获取目录以及子目录中的内容
}
}
}
public static void main(String[] args) throws IOException {
show(new File("D:/一级目录"));
}
}