1. Related libraries
The file-related library is also File, and most of the commonly used methods are encapsulated and can be used directly.
2. Examples
Add, delete, modify and check files through an example:
/**
* 文件操作示例类
*/
public class FileDemo {
public static void main(String[] args) throws IOException {
// 判断文件是否存在
File file = new File("D:/dir/file1.txt");
System.out.println("是否存在:" + file.exists());
// 创建文件
file.createNewFile();
// 判断类型
System.out.println("是否目录:" + file.isDirectory());
System.out.println("是否文件:" + file.isFile());
// 获取路径
System.out.println("绝对路径:" + file.getPath());
// 重命名
file.renameTo(new File("D:/dir/file_1.txt"));
// 删除
File file_1=new File("D:/dir/file_1.txt");
file_1.delete();
}
}
3. Code explanation
It should be noted that after the renaming is successful, if you want to delete the file, you need to redefine an object to point to the renamed file.
Through the breakpoint debugging, we can also find that after the rename is successful, the file object still points to file1.txt.