案例一:路径分隔符,名称分隔符
1 package com.bjsxt.io.file; 2 3 import java.io.File; 4 5 /** 6 * 两个常量 7 * 1、路径分隔符 ; 8 * 2、名称分隔符 (windows) /(Linux等) 9 * 10 */ 11 public class Demo01 { 12 public static void main(String[] args) { 13 System.out.println(File.pathSeparator); // ; 14 System.out.println(File.separator); // 15 //路径表示形式 16 String path = "E:\xp\test\2.jpg"; 17 path = "E:"+File.separator+"xp"+File.separator+"test"+File.separator+"2.jpg"; 18 19 } 20 21 }
案例二:绝对路径与相对路径构造File对象
1 package com.bjsxt.io.file; 2 3 import java.io.File; 4 5 /** 6 * 相对路径与绝对路径构造File对象 7 * 1、相对路径 8 * 2、绝对路径 9 * 10 * 11 */ 12 public class Demo02 { 13 public static void main(String[] args) { 14 String parentPath = "E:/xp/test"; 15 String name = "2.jpg"; 16 //相对路径 17 File src = new File(parentPath,name); 18 src = new File(new File(parentPath),name); 19 //输出 20 System.out.println(src.getName()); //2.jpg 21 System.out.println(src.getPath()); //E:xp est2.jpg 22 23 //绝对路径 24 src = new File("E:/xp/test/2.jpg"); 25 //输出 26 System.out.println(src.getName()); //2.jpg 27 System.out.println(src.getPath()); //E:xp est2.jpg 28 29 //没有盘符:以user.dir构建 30 src = new File("test.txt"); 31 System.out.println(src.getName()); //test.txt 32 System.out.println(src.getPath()); //test.txt 33 System.out.println(src.getAbsolutePath()); //E:gaoqi-workspaceIO est.txt 34 } 35 }