Java文件类String getPath()方法(带示例)
文件类字符串getPath()
软件包java.io.File.getPath()中提供了此方法。
此方法用于返回文件对象的路径。
该方法的返回类型为String,因此它以字符串形式返回文件对象的路径。
在此方法中,如果我们在文件对象中未提及完整路径,它将返回完整路径。
此方法不会引发异常。
语法:
String getPath(){
}参数:
我们不会在File方法中将任何对象作为参数传递。
返回值:
该方法的返回类型为String,因此它以String形式返回文件对象的路径。
Java程序演示getPath()方法示例
//导入File类,因为我们将使用File类方法
import java.io.File;
//导入Exception类,因为它可能会引发
//处理文件时出现异常
import java.lang.Exception;
public class GetPath {
public static void main(String[] args) {
try {
//指定文件的路径,我们使用双斜杠
//为Windows转义'\'字符序列
File file1 = new File("C:\\Users\\computer clinic\\OneDrive\\Articles\\myjava.txt");
File file2 = new File("java.txt");
//通过使用getPath()return文件对象的路径。
String path1 = file1.getPath();
//如果给定路径完整,则显示文件对象的路径。
System.out.println("The path of the file 1 if given path is complete :" + " " + path1);
//通过使用getPath()返回File对象的路径
//甚至我们都没有给[ie(java.txt)]
String path2 = file2.getPath();
//如果给定的路径不是绝对的,则显示文件对象的路径。
System.out.println("The path of the file2 if given path is not absolute :" + " " + path2);
} catch (Exception e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}输出结果
D:\Programs>javac GetPath.java D:\Programs>java GetPath The path of the file 1 if given path is absolute : C:\Users\computer clinic\OneDrive\myjava.txt The path of the file2 if given path is not absolute : D:\Programs\java.txt