File
类常用API和Java IO
相关基础知识
一、File类的常用操作
1. 构造方法
public File(String pathname);//通过将给定的字符串路径名
public File(String parent, String child);//通过给定的字符父级串路径和字符串子级路径
public File(File parent, String child);//通过父级抽象路径名和字符串子路径
2.获取文件信息常用API
//根据文件路径获取文件对象
File file = new File("E:\\AWei\\data\\applogs\\xxl-job");
//检测文件是否存在
boolean exists = file.exists();
//获取文件绝对路径
String absolutePath = file.getAbsolutePath();
//获取文件绝对长度(即文件大小,单位为字节)
long length = file.length();
//获取文件最后修改时间
long lastModified = file.lastModified();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String lastTime = dateFormat.format(new Date(lastModified));
//检测文件是否可读
boolean canRead = file.canRead();
//检测文件是否可写
boolean canWrite = file.canWrite();
//检测文件是否可执行
boolean canExecute = file.canExecute();
//获取文件相对路径
String path = file.getPath();
//获取文件父目录路径
String parent = file.getParent();
//获取文件父目录文件对象
File parentFile = file.getParentFile();
//判断文件是否为目录
boolean directory = file.isDirectory();
//判断文件是否为正常的文件
boolean isFile = file.isFile();
//判断文件是否隐藏
boolean hidden = file.isHidden();
3. 如何创建文件
注:创建文件时必须保证文件的父目录存在
File newFile = new File("F:\\test\\stu\\new.txt");
File parentFile = newFile.getParentFile();
if(!parentFile.exists()){//通常会与创建目录的方法配合使用
//创建父级目录,但只能创建一级
// parentFile.mkdir();
//创建多级父级目录
parentFile.mkdirs();
}
if(!newFile.exists()){
try {
//创建文件时,必须保证改文件的父级目录存在,否则,创建将报IO异常
boolean success = newFile.createNewFile();
System.out.println("文件创建是否成功:" + success);
} catch (IOException e) {
e.printStackTrace();
}
二、递归实现对目录(文件夹)的操作
1. 递归
2. 删除文件夹
使用递归调用自身,删除子目录
//递归遍历文件夹
public static void recursiveFolder(File folder){
if(folder.isDirectory()){//检测是否是文件夹
File[] files = folder.listFiles();
for(File file: files){
if(file.isDirectory()){//如果是文件夹,就再调用方法进行查看
recursiveFolder(file);
} else {
System.out.println(file.getPath());
}
}
} else {//不是文件夹就直接打印文件的路径
System.out.println(folder.getPath());
}
}
三、I/O流(重点)
1.分类
-
字节流
字节输入流:InputStream ----- FileInputStream
字节输出流:OutputStream ----- FileOutputStream
-
字符流
字符输入流:Reader ----- FileReader
字符输出流:Writer ----- FileWriter
注:在FileWriter中也调用了FileInputStream,所以字符流的本质也是字节流
新:读取字符,能用字符数组接收
-
缓冲流
缓冲输入流: BufferedReader(new FileReader)
缓冲输出流: BufferedWriter(new FileWriter)
**新:能够按行读取(readLine)、写入(newLine)**数据
-
对象流(将对象存储到文件中叫做序列化)
对象输入流:ObjectInputSteam (new FileInputSteam)
对象输出流:ObjectOutputSteam (new FileOutputSteam)
注:
- 将磁盘中存储的对象信息读入内存中的过程称之为反序列化,需要注意的是,反序列化必须保证与序列化时使用的JDK版本一致
- 需要序列化的类必须实现Serializable接口