相对于Java中的绝对路径 [英] Relative to absolute path in java

查看:80
本文介绍了相对于Java中的绝对路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要在我的项目中使用的文件,该文件位于资源包中

I have have a file that I want to use in my project which is in the resources package

src.res

按照此答案中所述,我相信我的代码是有效的.

Following what was stated in this answer, I believe that my code is valid.

File fil = new File("/res/t2.nii");
// Prints C:\\res\\t2.nii
System.out.println(fil.getAbsolutePath());  

问题是我文件不在我的项目文件中,所以出现异常.

The problem is that I that file is in my projects file not there, so I get an Exception.

我应该如何正确地将相对路径转换为绝对路径?

How am I suppose to properly convert from relative path to absolute?

推荐答案

由于您使用的是Java包,因此如果要加载资源,则必须使用类加载器.例如:

Since you are using a Java package, you must to use a class loader if you want to load a resource. e.g.:

URL url = ClassLoader.getSystemResource("res/t2.nii");
if (url != null) {
    File file = new File(url.toURI());
    System.out.println(file.getAbsolutePath());
}

您会注意到,ClassLoader.getSystemResource("res/t2.nii")返回用于读取资源的URL对象;如果找不到该资源,则返回null.下一行将给定的URL转换为抽象路径名.

You can notice that ClassLoader.getSystemResource("res/t2.nii") returns URL object for reading the resource, or null if the resource could not be found. The next line convertes the given URL into an abstract pathname.

在Java中加载资源的首选方式中了解更多信息.

这篇关于相对于Java中的绝对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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