File类是整个java.io包里面唯一一个与文件本身有关的操作类,可对文件路径进行指派,还可以获取文件相关的信息内容
注意:在使用File类指派操作文件的时候,文件的路径有可能不存在,只要不进行各种信息的获取
常用方法
File file = new File("d://test-io.txt");
if (file.exists()){
System.out.println(file.delete());
}else {
System.out.println(file.createNewFile());
}
使用File类需要注意的两个问题
- 当前的程序是进行了磁盘文件的处理操作,可能存在延迟
- Java本身采用开平台的编程模式,这总情况下必须考虑各种系统的路径问题
- windows路径系统分隔符:""
- UNIX,类UNIX(Linux,MacO等)分隔符为:"/"
但是在代码编写过程中每次编写大量的“//”或“\”进行转义处理显得非常麻烦,因此在File类中提供了一个常量:
范例:
File file = new File("d:"+File.pathSeparator+"test-io.txt");
if (file.exists()){
System.out.println(file.delete());
}else {
System.out.println(file.createNewFile());
}