如何在 Java 中知道實際檔案儲存在哪裡?
在 Java 中,您可以使用 File 類來表示和操作檔案和目錄路徑。您還可以使用 File 類來建立、刪除和操作檔案和目錄。
要了解實際檔案在 Java 中儲存在哪裡,可以使用 File 類的 getAbsolutePath() 方法。此方法返回檔案的絕對路徑的字串表示形式,其中包括從根目錄到檔案的完整路徑。
讓我們深入瞭解本文,看看實際檔案在 Java 中儲存在哪裡。
例如
假設原始檔為
" example.txt”
執行獲取實際檔案儲存位置的操作後,結果將為
檔案的絕對路徑:C:\Users\SAMPLE \Desktop\satya\Program\example.txt
演算法
步驟 1:宣告並初始化原始檔路徑。
步驟 2:使用 getAbsolutePath() 方法獲取實際檔案的位置。
步驟 3: 列印結果。
語法
getAbsolutePath():它是 Java API 中 File 類的一個方法,它將檔案或目錄的絕對路徑作為字串返回。
多種方法
我們提供了不同的方法來解決這個問題。
1. 使用靜態方法
2. 使用使用者定義的方法
讓我們逐一檢視程式及其輸出。
方法 1:使用靜態方法
在這種方法中,透過傳遞檔名來初始化 File 類物件。然後根據演算法,使用 getAbsolutePath() 方法獲取檔案在 Java 中儲存的絕對路徑。
示例
import java.io.File;
public class Main
{
//main method
public static void main(String[] args)
{
File file = new File("example.txt");
//getting the location of actual file
String absolutePath = file.getAbsolutePath();
//print the result
System.out.println("Absolute path of file: " + absolutePath);
}
}
輸出
Absolute path of file: /home/cg/root/64927fe34456a/example.txt
方法 2:使用使用者定義的方法
在這種方法中,從 main 方法呼叫使用者定義的方法。在使用者定義的方法中,透過傳遞檔名來初始化 File 類物件。然後根據演算法,使用 getAbsolutePath() 方法獲取檔案在 Java 中儲存的絕對路徑。
示例
import java.io.File;
public class Main
{
//main method
public static void main(String[] args)
{
//calling user defined method
func();
}
//user defined method
static void func()
{
//getting the file path
File file = new File("myfile.txt");
//getting the location of actual file
String absolutePath = file.getAbsolutePath();
//print the result
System.out.println("Absolute path of file: " + absolutePath);
}
}
輸出
Absolute path of file: /home/cg/root/64927fe34456a/myfile.txt
在這篇文章中,我們探討了如何使用 Java 程式語言來了解實際檔案儲存在哪裡。
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP