无法从资源获取绝对文件路径 [英] Not getting absolute file path from resources

查看:83
本文介绍了无法从资源获取绝对文件路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在/src/main/resources下有一个模板文件,我想获取它的绝对路径,问题是我得到的是相对路径而不是绝对路径.

I have a template file under /src/main/resources and i want to get the absolute path of it, the problem is that I'm getting a relative path and not a absolute path.

在项目中加载模板后,我需要获取计算机中文件的绝对路径.我现在正在做的是这样:

I need to get the absolute path of the file in my computer after loading the template inside the project. What I'm doing now is this:

URL location = this.getClass().getResource("/template/template2.vm"); 
String fullPath = location.getPath();

这将返回: (java.lang.String)vfs:/content/MyProyect-1.0.0-SNAPSHOT.war/WEB-INF/classes/templates/template2.vm

This returns: (java.lang.String) vfs:/content/MyProyect-1.0.0-SNAPSHOT.war/WEB-INF/classes/templates/template2.vm

如果在Eclipse中进行操作,它将提供完整路径,但是在Netbeans中且没有IDE进行部署将返回此结果.我正在使用jboss进行部署.

If you do it in Eclipse it gives the full path, but deploying in Netbeans and without an IDE returns this result. I'm using jboss for deploying.

我也尝试过

String fullPath = location.getAbsolutePath();

我一直得到这个结果.

推荐答案

JBoss如前所述正在使用虚拟文件系统(VFS).您可以使用jboss专用库jboss-vfs获取文件的绝对路径.

JBoss is using Virtual File System (VFS) as stated before. You can get absolute path to file using jboss specific library jboss-vfs.

  URL rootUrl = classLoader.getResource(path);
  VirtualFile jbossVirtualFile = (VirtualFile) rootUrl.getContent();
  File fileSystemFile = jbossVirtualFile.getPhysicalFile();
  String absolutePathToFile = fileSystemFile.getPath();

这里我使用的是jboss-vfs 3.2.4.Final.

Here im using jboss-vfs 3.2.4.Final.

或者,如果您需要读取文件并且不关心路径使用

Alternatively if you need to read file and do not care about path use

  classLoader.getResourceAsStream(path) 

(这不适用于Dirs.)

(This does not work for dirs.)

这篇关于无法从资源获取绝对文件路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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