Java File getAbsolutePath()方法及示例
getAbsolutePath() 方法是File类的一部分。这个函数返回给定文件对象的绝对路径名。如果文件对象的路径名是绝对的,那么它只是返回当前文件对象的路径。
例如: 如果我们使用 “program.txt “的路径创建一个文件对象,它将指向保存可执行程序的同一目录下的文件(如果你使用的是IDE,它将指向你保存程序的文件)。这里,上述文件的路径是 “program.txt”,但这个路径不是绝对的(即不完整)。函数getAbsolutePath()将返回来自根目录的绝对(完整)路径。如果文件对象是以绝对路径创建的,那么getPath()和getAbsolutePath()将给出相同的结果。
函数签名 。
public String getAbsolutePath()
函数语法 。
file.getAbsolutePath()
参数: 该函数不接受任何参数。
返回值: 该函数返回一个字符串值,它是给定文件对象的绝对路径。
异常: 如果不能访问所需的属性值,该方法会抛出 安全异常 。
下面的程序将说明getAbsolutePath()方法的使用。
例1: 在当前工作目录下有一个名为 “program.txt “的文件。
// Java program to demonstrate the// use of getAbsolutePath() function import java.io.*; public class solution { public static void main(String args[]) { // try-catch block to handle exceptions try { // Create a file object File f = new File("program.txt"); // Get the absolute path of file f String absolute = f.getAbsolutePath(); // Display the file path of the file object // and also the file path of absolute file System.out.println("Original path: " + f.getPath()); System.out.println("Absolute path: " + absolute); } catch (Exception e) { System.err.println(e.getMessage()); } }}
输出
Original Path: program.txtAbsolute Path: C:\Users\pc\eclipse-workspace1\arnab\program.txt

例2: 在当前工作目录下有一个名为 “程序 “的目录。
// Java program to demonstrate the// use of getAbsolutePath() function import java.io.*; public class solution { public static void main(String try-catch { // try catch block to handle exceptions try { // Create a file object File f = new File("program"); // Get the absolute path of file f String absolute = f.getAbsolutePath(); // Display the file path of the file object // and also the file path of absolute file System.out.println("Original path: " + f.getPath()); System.out.println("Absolute path: " + absolute); } catch (Exception e) { System.err.println(e.getMessage()); } }}输出
Original Path: programAbsolute Path: C:\Users\pc\eclipse-workspace1\arnab\program

例3: 在 “f:\”目录下有一个名为 “f:\program.txt “的文件。
// Java program to demonstrate the// use of getAbsolutePath() function import java.io.*; public class solution { public static void main(String args[]) { // try catch block to handle exceptions try { // Create a file object File f = new File("f:\\program.txt"); // get the absolute path // of file f String absolute = f.getAbsolutePath(); // display the file path of the file object // and also the file path of absolute file System.out.println("Original path: " + f.getPath()); System.out.println("Absolute path: " + absolute); } catch (Exception e) { System.err.println(e.getMessage()); } }}输出
Original file path: f:\program.txtAbsolute file path: f:\program.txt

这些程序可能无法在在线IDE中运行。请使用离线IDE,并设置文件的路径
