文件操作
文件创建
package com.edu.file;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.IOException;
public class Demo01 {
public static void main(String[] args) {
}
@Test
//方式1
public void create01(){
String filePath = "D:\\new1.txt";
File file = new File(filePath);
try {
file.createNewFile();
} catch (IOException e) {
throw new RuntimeException(e);
}
System.out.println("创建成功");
}
@Test
//方式二
public void create02(){
File file = new File("d:\\"); //父
String fileName = "new2.txt";//子
File file1 = new File(file,fileName);
try {
file1.createNewFile(); //真正创建
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Test
//方式三
public void crete03(){
String parentPath = "d:\\";
String sonPath = "new3.txt";
File file = new File(parentPath,sonPath);
try {
file.createNewFile();
} catch (IOException e) {
throw new RuntimeException(e);
}
System.out.println("创建成功");
}
}
获取文件信息
//获取文件信息
public void info(){
//先创建文件对象
File file = new File("d:\\new3.txt");
//调用相应方法得到对应信息
System.out.println("文件名字:"+file.getName());
System.out.println("文件绝对路径"+file.getAbsolutePath());
System.out.println("文件父目录"+file.getParent());
System.out.println("文件大小"+file.length());
System.out.println("文件是否存在"+file.exists());
System.out.println("是不是一个文件"+file.isFile());
System.out.println("是不是一个目录"+file.isDirectory());
}