Java File isAbsolute()方法及示例

来源:这里教程网 时间:2026-02-17 20:54:08 作者:

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并设置文件的父文件

相关推荐