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\源代碼 }