JAVA获取文件绝对路径的方法

发布时间:2026-09-28 19:09:35 浏览次数:2

获取Java文件的绝对路径可助于在程序中读取或写入文件。下面将详细介绍Java中获取文件绝对路径的方法。

1. 通过File类的getAbsolutePath()方法获取文件路径

使用File类的getAbsolutePath()方法获取文件的绝对路径非常简单,只需要将文件对象作为参数传入即可。示例如下:

File file = new File("test.txt");String absolutePath = file.getAbsolutePath();System.out.println("文件的绝对路径:" + absolutePath);

2. 通过Class.getResource()方法获取文件路径

Class.getResource()方法可用于获取类路径中的资源,如果使用相对路径"/"前缀,则会自动转为以类路径作为根路径。此方法返回的是一个URL类型的对象,如果需要获取文件的绝对路径,则需要先获取URL,再通过URLConnection对象获取路径。示例如下:

String fileName = "test.txt";URL url = Class.class.getResource("/" + fileName);if(url != null){    try {        URLConnection connection = url.openConnection();        connection.connect();        File file = new File(connection.getURL().getFile());        String absolutePath = file.getAbsolutePath();        System.out.println("文件 \"" + fileName + "\" 的绝对路径:" + absolutePath);    } catch (IOException e) {        e.printStackTrace();    }}else{    System.out.println("文件 \"" + fileName + "\" 不存在");}
需要做网站?需要网络推广?欢迎咨询客户经理 13272073477