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

查看:3883
本文介绍了如何获取项目的/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();

OR

尽管这可能并非始终有效,但更简单的解决方案-

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天全站免登陆