java里getPath、 getAbsolutePath、getCanonicalPath的區別


本文鏈接:https://blog.csdn.net/wh_19910525/article/details/9314675


File的這三個方法在api中都有說明,僅以程序為例說明。

package test;

import java.io.File;
import java.io.IOException;

public class TestFilePath {

 
 public static void main(String[] args) {
  // TODO Auto-generated methodstub

  System.out.println(System.getProperty("user.dir"));
  
  try {
   System.out.println("-----默認相對路徑:取得路徑不同------");
   File file1 =new File("..\\src\\test1.txt");
   System.out.println(file1.getPath());
   System.out.println(file1.getAbsolutePath());
   System.out.println(file1.getCanonicalPath());
   System.out.println("-----默認相對路徑:取得路徑不同------");
   File file =new File(".\\test1.txt");
   System.out.println(file.getPath());
   System.out.println(file.getAbsolutePath());
   System.out.println(file.getCanonicalPath());
   
   System.out.println("-----默認絕對路徑:取得路徑相同------");
   File file2 =new File("D:\\workspace\\test\\test1.txt");
   System.out.println(file2.getPath());
   System.out.println(file2.getAbsolutePath());
   System.out.println(file2.getCanonicalPath());
  } catch (IOException e) {
   // TODOAuto-generated catch block
   e.printStackTrace();
  }
 }

}

程序執行結果如下:

F:\eclipseworkspace\testejb
-----默認相對路徑:取得路徑不同------
..\src\test1.txt
F:\eclipseworkspace\testejb\..\src\test1.txt
F:\eclipseworkspace\src\test1.txt
-----默認相對路徑:取得路徑不同------
.\test1.txt
F:\eclipseworkspace\testejb\.\test1.txt
F:\eclipseworkspace\testejb\test1.txt
-----默認絕對路徑:取得路徑相同------
D:\workspace\test\test1.txt
D:\workspace\test\test1.txt
D:\workspace\test\test1.txt
結論:

當輸入為絕對路徑時,返回的都是絕對路徑。

當輸入為相對路徑時:

getPath()返回的是File構造方法里的路徑,是什么就是什么,不增不減

getAbsolutePath()返回的其實是user.dir+getPath()的內容,從上面F:\eclipseworkspace\testejb、F:\eclipseworkspace\testejb\..\src\test1.txt、F:\eclipseworkspace\testejb\.\test1.txt可以得出。

getCanonicalPath()返回的就是標准的將符號完全解析的路徑

————————————————
版權聲明:本文為CSDN博主「wh_19910525」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/wh_19910525/article/details/9314675


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM