public class demo1File {
public static void main(String[] args) {
String pathSeparator = File.pathSeparator;
System.out.println(pathSeparator);//路径分隔符,输出分号 ;
String separator = File.separator;
System.out.println(separator);//文件名称分隔符,输出反斜杠 \
}
}
路径:
绝对路径:一个完整的路径
以盘符开始的路径,如 C:\\Users\\qq\\a.txt
相对路径:一个简化的路径
相对指的是相对于当前项目的根目录
如果使用当前项目的根目录,路径可以简化书写
C:\\Users\\qq\\a.txt简化为 a.txt(可以省略项目的根目录)
注意:
1.路径不区分大小写
2.路径中的文件分隔符Windows使用反斜杠,反斜杠是转义字符,两个反斜杠代表一个\
构造方法:
第一种:
/*
File(String pathname) 通过将给定路径名字符串转换为抽象路径名来创建一个新 File 实例。
参数 :
String pathname 字符串的路径名称
路径可以是以文件结尾,也可以是以文件夹结尾
路径可以是存在,也可以不存在
创建File对象,只是把字符串路径封装为File对象,不考虑路径的真假情况
*/
private static void show01() {
File f1= new File("C:\\Users\\qq\\a.txt");
System.out.println(f1);//输出路径,重写了Object类的toString方法
//可以输出文件路径
File f2= new File("C:\\Users\\qq");
System.out.println(f2);
//可以输出文件夹路径
File f3= new File("a.txt");
System.out.println(f3);
//可以输出相对路径
}
第二种:
/*
File(String parent, String child) 根据 parent 抽象路径名和 child 路径名字符串创建一个新 File 实例。
参数:把路径分成了两部分
String parent:父路径
String child :子路径
好处:
父路径和子路径可以单独书写,使用起来非常灵活,父路径和子路径都可以变化
*/
private static void show02(String parent,String child) {
File file = new File(parent,child);
System.out.println(file);
}//调用时需传入两个表示路径的字符串,如 show02("C:\\","a.txt");
第三种:
/*
File(File parent, String child) 根据 parent 抽象路径名和 child 路径名字符串创建一个新 File 实例。
参数:把路径分成了两部分
File parent :父路径
String child :子路径
好处:
父路径和子路径可以单独书写,使用起来非常灵活,父路径和子路径都可以变化
父路径是File类型,可以使用File的方法对路径进行操作,再使用路径创建对象
*/
private static