更新時間:2022-09-02 11:52:17 來源:動力節點 瀏覽6284次
本教程介紹如何在 Java 中定義相對路徑。
相對路徑是不完整的路徑(沒有根目錄),結合當前目錄路徑訪問資源文件。相對路徑不以文件系統的根元素開頭。
我們使用相對路徑來定位文件在當前目錄或父目錄,或同一層次結構中。
定義相對路徑有幾種方法,例如./引用當前目錄路徑,../直接父目錄路徑等。讓我們看一些例子。
我們可以使用相對路徑來定位當前工作目錄中的文件資源。請參見下面的示例。
import java.io.File;
public class SimpleTesting{
public static void main(String[] args) {
String filePath = "files/record.txt";
File file = new File(filePath);
String path = file.getPath();
System.out.println(path);
}
}
輸出:
files/record.txt
我們可以使用../帶有文件路徑的前綴來定位父目錄中的文件。這是訪問父目錄中文件的相對路徑。請參見下面的示例。
import java.io.File;
public class SimpleTesting{
public static void main(String[] args) {
String filePath = "../files/record.txt";
File file = new File(filePath);
String path = file.getPath();
System.out.println(path);
}
}
輸出:
../files/record.txt
如果文件資源位于當前目錄,我們可以使用./帶路徑的前綴來創建相對文件路徑。請參見下面的示例。
import java.io.File;
public class SimpleTesting{
public static void main(String[] args) {
String filePath = "./data-files/record.txt";
File file = new File(filePath);
String path = file.getPath();
System.out.println(path);
}
}
輸出:
./data-files/record.txt
如果文件位于目錄結構的上兩層,則使用../../帶有文件路徑的前綴。請參見下面的示例。
import java.io.File;
public class SimpleTesting{
public static void main(String[] args) {
String filePath = "../../data-files/record.txt";
File file = new File(filePath);
String path = file.getPath();
System.out.println(path);
String absPath = file.getAbsolutePath();
System.out.println(absPath);
}
}
輸出:
../../data-files/record.txt
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習