import java.io.File;
public class FilePathExample {
public static void main(String[] args) {
// 创建一个File对象,表示文件或目录
File file = new File("example.txt");
// 获取文件的绝对路径
String absolutePath = file.getAbsolutePath();
System.out.println("绝对路径: " + absolutePath);
// 获取文件的规范路径(去掉冗余部分)
try {
String canonicalPath = file.getCanonicalPath();
System.out.println("规范路径: " + canonicalPath);
} catch (Exception e) {
e.printStackTrace();
}
// 获取文件的父路径
String parentPath = file.getParent();
System.out.println("父路径: " + parentPath);
// 获取文件名
String fileName = file.getName();
System.out.println("文件名: " + fileName);
}
}
new File("example.txt")
创建一个表示文件或目录的File
对象。getAbsolutePath()
方法获取文件的绝对路径,即从根目录到文件的完整路径。getCanonicalPath()
方法获取文件的规范路径,它会去掉路径中的冗余部分(如.
和..
),并解决符号链接问题。注意这个方法可能会抛出异常,因此需要捕获异常。getParent()
方法获取文件的父目录路径。getName()
方法获取文件名(包括扩展名)。上一篇:java中arraylist用法
下一篇:java计算两个时间之间的天数
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站