如何获取项目/resources文件夹中文件的绝对路径 [英] How to get absolute path to file in /resources folder of your project

查看:78
本文介绍了如何获取项目/resources文件夹中文件的绝对路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设标准的 maven 设置.

Assume standard maven setup.

假设在您的资源文件夹中有一个文件 abc.

Say in your resources folder you have a file abc.

在 Java 中,如何获取文件的绝对路径?

In Java, how can I get absolute path to the file please?

推荐答案

您可以使用 ClassLoader.getResource 方法来获取正确的资源.

You can use ClassLoader.getResource method to get the correct resource.

URL res = getClass().getClassLoader().getResource("abc.txt");
File file = Paths.get(res.toURI()).toFile();
String absolutePath = file.getAbsolutePath();

虽然这可能不会一直奏效,但有一个更简单的解决方案 -

Although this may not work all the time, a simpler solution -

您可以创建一个 File 对象并使用 getAbsolutePath 方法:

You can create a File object and use getAbsolutePath method:

File file = new File("resources/abc.txt");
String absolutePath = file.getAbsolutePath();

这篇关于如何获取项目/resources文件夹中文件的绝对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆