Not getting absolute file path from resources

一世执手 提交于 2021-02-08 06:29:15

问题


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();

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

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.

I've also tried doing

String fullPath = location.getAbsolutePath();

and i keep getting this result.


回答1:


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();

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) 

(This does not work for dirs.)




回答2:


Is this always going to be local? If so can you do this:

URL location = this.getClass().getResource(/template/template2.vm); 
File f = new File(location.toUri());
String fullPath = f.getAbsolutePath();



回答3:


I think this is not possible. JBoss uses different systems for storing deployed files. vfs is one them. I had the same problem some months ago and was not able to solve it, even after a lot of research. I ended up with adding an environment variable when starting jboss pointing to the directory I needed (I needed to load a .properties file, which was outside of the deployment). See here: https://community.jboss.org/wiki/PropertiesService



来源:https://stackoverflow.com/questions/22567174/not-getting-absolute-file-path-from-resources

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!