1. 分隔符:
* 路径分隔符:pathSeparator --> ;
* 名称分隔符:separator --> windows(\),linux等(/)
public static void main(String[] args) {
String str = File.pathSeparator;
String str2 = File.separator;
System.out.println(str);// Output: ;
System.out.println(str2);// Output: \
}
2. * 构建文件对象:
* 1)相对路径构建:File(String parent, String child)
File(File parent, String child)
* 2)绝对路径构建:File(String pathname)
* 分隔符的使用举例:
* 1. "Android\\源代码\\2.jpg" 这里用双斜线是因为单斜线表示转义字符
* 2. "Android"+File.separator+"源代码"+File.separator+"2.jpg" 适合动态生成的时候使用,优点是跨平台
* 3. "Android/源代码/2.jpg" 这是推荐方式。
* 疑惑:windows下不是使用"\"为分隔符吗,为什么能使用其他平台下的"/"分隔符?
* 解释:在windows下,用在java中相当于 \\==/。因此第一种和第三种写法是等效的。
public static void main(String[] args) { // 相对路径构建File对象 String parentPath = "F:\\计算机技术\\Android\\源代码"; String name = "2.jpg";// 2.jpg可以不存在,不报错。因为只是建立对象而已 // File(String parent, String child) File file = new File(parentPath, name); System.out.println(file.getName()); System.out.println(file.getAbsolutePath()); // File(File parent, String child) File file2 = new File(new File(parentPath), name); // 绝对路径构造File对象 File file3 = new File("F:/计算机技术/Android/源代码"); // 如果不写盘符地创建绝对路径File对象,是会在user.dir,即当前文件夹下创建。 File file4 = new File("计算机技术"+File.separator+"Android"+File.separator+"源代码"); System.out.println(file3.getParent()); System.out.println(file3.getAbsolutePath());// Output:F:\计算机技术\Android\源代码 System.out.println(file4.getAbsolutePath()); // Output:F:\计算机技术\Android\Eclipse WorkPlace\IOProject\计算机技术\Android\源代码 }