File类是java.io包中唯一代表磁盘文件本身对象,定义了与平台无关的方法来操作文件,可以新建,删除等操作,但不能访问文件内容。
1.exists()
判断文件路径是否存在
public class FileTest {
public static void main(String[] args) {
File f = new File("D\\file");
System.out.println(f.exists());//false
}
2.createNewFile()
创建文件
public class FileTest {
public static void main(String[] args) throws IOException {
File f = new File("D:\\file");
if(!f.exists()){//如果不存在 创建文件
f.createNewFile();
}
}
}
3.mkdir()
创建目录
public class Test {
public static void main(String[] args) throws IOException {
File f = new File("C:\\file");
if(!f.exists()){//如果文件不存在 以目录形式创建
f.mkdir();
}
}
}
4.getParent()
获取父路径
public class Test {
public static void main(String[] args) {
File f2 = new File("C:\\Users\\86139\\.p2");
System.out.println(f2.getParent());//获取父路径C:\Users\86139
}
}
5.getAbsolutePath()
获取绝对路径
public class Test {
public static void main(String[] args) {
File f2 = new File("C:\\Users\\86139\\.p2");
System.out.println(f2.getAbsolutePath());//获取绝对路径C:\Users\86139\.p2
}
}
6.isDirectory()
判断是否是一个目录
public class Test {
public static void main(String[] args) {
File f2 = new File("C:\\Users\\86139\\.p2");
System.out.println(f2.isDirectory());//是否是一个目录 true
}
}
7.isFile()
判断是否是一个文件
public class Test {
public static void main(String[] args) {
File f2 = new File("C:\\Users\\86139\\.p2");
System.out.println(f2.isFile());//判断是否是一个文件 false
}
}
8.lastModified()
获取最后一次修改时间 1970年到现在的总毫秒数
public class Test {
public static void main(String[] args) {
File f2 = new File("C:\\Users\\86139\\.p2");
long time = f2.lastModified();//
Date date = new Date(time);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
String s = sdf.format(date);
System.out.println(s);//2021-12-25 09:07:00 281
}
}
9.length()
获取文件大小 字节
public class Test {
public static void main(String[] args) {
File f2 = new File("C:\\AMTAG.BIN");
System.out.println(f2.length());//获取文件大小
}
}
10.listFiles()
获取当前目录下所有子文件
public class Test {
public static void main(String[] args) {
File f2 = new File("D:\\app");
File[] files = f2.listFiles();
for(File file : files){
System.out.println(file.getAbsolutePath());
}
}
}
11.delete()
删除一个文件
public class Test {
public static void main(String[] args) {
File f = new File("D:\\file.txt");
System.out.println(f.delete());//true 删除成功
}
}
12.getName()
获取文件名
public class Test {
public static void main(String[] args) {
File f = new File("C:\\Users\\86139\\.p2");
System.out.println(f.getName());//.p2
}
}