5

I'm loading a properties using below code:

ResourceBoundle boundle = ResourceBundle.getBundle("file")

I want to know the absolute path of the loaded file. For example if I execute this code in a web application in webapps folder of a tomcat I want to obtain:

c:\tomcat8\webapps\example\WEB-INF\classes\file.properties.

How can I know this path?

fealfu
  • 71
  • 5

2 Answers2

0

I have 'resolved' my problem with this post 'Getting current working directory'. For my problem I only need this, once I know the working directory I can find the absolute path

public class Test {
public static void main(String... args) throws Exception {
    URL location = Test.class.getProtectionDomain().getCodeSource().getLocation();
    System.out.println(location.getFile());
}}

I think that perhaps this solution does not cover all the situations, but it is enough for me.

Community
  • 1
  • 1
fealfu
  • 71
  • 5
0

You can't get the physical location from a ResourceBundle, but if you know the path that was used to load it, then you can find out the physical location of that. Like this:

String resourceToLoad = "file";
URL url = this.getClassLoader().getResource(resourceToLoad);
ResourceBoundle bundle = ResourceBundle.getBundle(resourceToLoad);

The url will have the physical location of the resource -- at least most of the time.

Remember that a ResourceBundle can also be backed by a Java class rather than something like a properties file. ClassLoader.getResource doesn't understand the mapping between ResourceBundle and Java classes. If you want to be able to support those, you'll have to implement a similar algorithm to what ResourceBundle does in order to search for classes that match it's scheme.

Christopher Schultz
  • 20,221
  • 9
  • 60
  • 77