當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Java File isAbsolute()用法及代碼示例

isAbsolute()方法是File類的一部分。該函數返回抽象路徑名是否為絕對路徑。

例如:如果我們使用“program.txt”路徑創建文件對象,則該文件對象指向存在於可執行程序所在目錄的文件(如果使用的是IDE,它將指向保存程序的文件) )。這裏上麵提到的文件的路徑是“program.txt”,但是該路徑不是絕對路徑(即不完整)。絕對路徑是根目錄的完整路徑。

函數簽名:


public boolean isAbsolute()

函數語法:

file.isAbsolute()

參數:該函數不接受任何參數。

返回值:該函數返回布爾值,該值指示抽象路徑名是否是絕對路徑。

下麵的程序將說明isAbsolute()函數的用法

範例1:給我們一個文件的文件對象,我們必須檢查它是否是絕對的

// Java program to demonstrate the 
// use of isAbsolute() 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("c:\\users\\program.txt"); 
  
            // Check if the given path 
            // is absolute or not 
            if (f.isAbsolute()) { 
  
                // Display that the path is absolute 
                // as the function returned true 
                System.out.println("The path is absolute"); 
            } 
            else { 
  
                // Display that the path is not absolute 
                // as the function returned false 
                System.out.println("The path is not absolute"); 
            } 
        } 
        catch (Exception e) { 
            System.err.println(e.getMessage()); 
        } 
    } 
}

輸出:

The path is absolute

範例2:給我們一個文件的文件對象,我們必須檢查它是否是絕對的

// Java program to demonstrate the 
// use of isAbsolute() 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"); 
  
            // Check if the given path 
            // is absolute or not 
            if (f.isAbsolute()) { 
  
                // Display that the path is absolute 
                // as the function returned true 
                System.out.println("The path is absolute"); 
            } 
            else { 
  
                // Display that the path is not absolute 
                // as the function returned false 
                System.out.println("The path is not absolute"); 
            } 
        } 
        catch (Exception e) { 
            System.err.println(e.getMessage()); 
        } 
    } 
}

輸出:

The path is not absolute

這些程序可能無法在在線IDE中運行。請使用離線IDE並設置文件的父文件



相關用法


注:本文由純淨天空篩選整理自andrew1234大神的英文原創作品 File isAbsolute() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。