Search code examples
javajsfpropertiespathrelative-path

Java relative path to file


I am building a JSF 2.2 project in Netbeans 7.4 (Windows 7 64bit) and one of my beans need to use a properties file located to the directory "/NetBeansProjects/projectName/web/WEB-INF/file.properties" while the bean that needs it is on the "/NetBeansProjects/projectName/src/java/packageName/bean.java". If I use an absolute path everything works like a charm but when I try to use a relative path it can not find the file. I tried to use every possible variation of "../../../web/WEB-INF/file.properties" but it just doesn't work. What should I do?


Solution

  • Use ExternalContext.getResourceAsStream() to pass context-relative path

    This should work:

    Properties prop = new Properties();
    ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
    prop.load(externalContext.getResourceAsStream("/WEB-INF/file.properties"));