Relative path for properties file

24,279

be sure that your property file is available to your compiled (.class) file and get it this way

getClass().getResource("filename.properties") // you get an URL, then openStream it

or

getClass().getResourceAsStream("filename.properties") // you get an InputStream

Example:

import java.net.URL;
public class SampleLoad {
    public static void main(String[] args) {
        final URL resource = SampleLoad.class.getResource("SampleLoad.class");
        System.out.println(resource);
    }
}

this main retrieves its own compiled version at runtime:

file:/C:/_projects/toolbox/target/classes/org/game/toolbox/SampleLoad.class

Share:
24,279
de3
Author by

de3

Updated on July 09, 2022

Comments

  • de3
    de3 almost 2 years

    I'm using a properties file:

    try 
    {
        properties.load(new FileInputStream("filename.properties"));
    } 
    catch (IOException e) 
    {
    }
    

    Where should I place filename.properties? I don't want to specify absolute path as this code has to work in different platforms. I tried to place it in the same directory as de class but it doesn't work. (Sorry if it's a stupid question)

    Maybe I can get the path where the current class is placed somehow?

  • de3
    de3 about 13 years
    Ok it works, but I have to remove 'file:/' from that path, so I have to replace "new FileInputStream(filename.properties)" in my code with: FileInputStream(resource.toString().substring("file:/".lengt‌​h(),resource.toStrin‌​g().length()))); `
  • Paul Webster
    Paul Webster about 13 years
    @de3, use @Guillaume's second form, getResourceAsStream(*). It will continue to work even if you ship your classes in a jar.