Java File getPath()方法及示例

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

Java File getPath()方法及示例

getPath() 方法是File类的一部分。这个函数返回给定文件对象的路径。该函数返回一个字符串对象,其中包含给定文件对象的路径。

函数签名

public String getPath()

函数语法

file.getPath()

参数: 该函数不接受任何参数。

返回值: 该函数返回一个字符串值,即给定文件对象的路径。

下面的程序将说明getPath()函数的使用。

例1: 我们得到了一个文件的对象,我们必须得到该文件对象的路径。

// Java program to demonstrate the// use of getPath() 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");              // Get the path of the given file f            String path = f.getPath();              // Display the file path of the file object            System.out.println("File path : " + path);        }        catch (Exception e) {            System.err.println(e.getMessage());        }    }}

输出

File path : c:\users\program.txt

例2: 我们得到了一个目录下的文件对象,我们必须得到该文件对象的路径。

// Java program to demonstrate the// use of getPath() 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");              // Get the path of the given file f            String path = f.getPath();              // Display the file path of the file object            System.out.println("File path : " + path);        }        catch (Exception e) {            System.err.println(e.getMessage());        }    }}

输出

File path : c:\users\program

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

相关推荐