File类不能完成文件的读和写。它是文件和路径名的抽象表现形式。
C:\lxc 这是一个File对象
C:\lxc\a\b\.1.txt 这也是一个FIle对象
File类的常用方法
(1)file.exists( ) 判断一个文件是否存在、file.mkdir( ) 创建一个文件夹
public class FileTest {
public static void main(String[] args) {
try {
// 先获取一个文件夹路径
String path = ResourceUtils.getURL("classpath:").getPath() + "static/css";
File file = new File(path);
// 如果不存在,则创建一个新文件夹
if(!file.exists()) {
file.mkdir();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
(2)file.mkdirs ( ) 创建多个目录
String path = ResourceUtils.getURL("classpath:").getPath() + "static/a/b/c";
File file = new File(path);
// 如果不存在,则创建多个新文件夹
if(!file.exists()) {
file.mkdirs();
}
(3)file.createNewFile( ) 以文件的形式创建一个文件
String path = ResourceUtils.getURL("classpath:").getPath() + "static/abc";
File file = new File(path);
// 如果不存在,则创建一个新文件夹
if(!file.exists()) {
file.createNewFile();
}
(4)file.getParent( ) 获取文件夹或文件的父级目录
// 获取文件或文件夹的父级目录
File file = new File(path);
System.out.println(file.getParent()); // D:\biancheng_files\Maven\spring_boot_01\target\classes\static
(5)file.getName( ) 获取文件名
String path = ResourceUtils.getURL("classpath:").getPath()+"static/1.txt";
File file = new File(path);
// 获取文件名称
String fileName = file.getName(); // 1.txt
(6)file.isDirectory( ) 判断是否是一个目录
(7)file.isFile( ) 判断是否是一个文件
(8)file.lastModified( ) 获取最后修改的时间
public class FileTest {
public static void main(String[] args) throws Exception{
String path = ResourceUtils.getURL("classpath:").getPath()+"static/1.txt";
File file = new File(path);
// 获取文件名称
String fileName = file.getName();
// 获取最后的需改时间
long lastModified = file.lastModified();
// 转化为正常时间
Date date = new Date(lastModified);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String formatTime = simpleDateFormat.format(date);
System.out.println(fileName + "最后的修改时间为:"+formatTime);
}
}
(9)file.length( ) 获取文件大小(返回文件字节大小)
String path = ResourceUtils.getURL("classpath:").getPath()+"static/1.txt";
File file = new File(path);
// 获取文件大小 -> 转kb
long fileSize = file.length(); // 42
System.out.println((double) fileSize/1024); // 0.041015625
(10)
file.listFiles() 获取一个文件下的所有文件路径;
file.getAbsolutePath() 获取文件的绝对路径。
String path = ResourceUtils.getURL("classpath:").getPath()+"static";
File file = new File(path);
// 获取static、文件夹下的所有文件路径
File[] fileList = file.listFiles(); //获取的是一个File类型的数组
for(File fileItem : fileList) {
System.out.println(fileItem.getAbsolutePath());
}