Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Path of properties file in java

I have a property file which is inside a default package and the class in which I am using the properties file is also in the same default package. If I use just the file name without any path I am getting error. Obviously that is not correct as I should give some kind of path to refer to tat file. I will build the application make it as a jar file so how should I give the path as the properties file should go inside that jar file. I am using Netbeans IDE.

EDIT

 Properties pro = new Properties();

    try {            
        pro.load(new FileInputStream("pos_config.properties"));
        pro.setProperty("pos_id", "2");
        pro.setProperty("shop_type", "2");
        pro.store(new FileOutputStream("pos_config.properties"), null);
        String pos_id = pro.getProperty("pos_id");
        if(pos_id.equals("")){
           pos_id="0" ;
        }
        global_variables.station_id = Integer.parseInt(pos_id);
        String shop_type = pro.getProperty("shop_type");
        if(shop_type.equals("")){
           shop_type="0" ;
        }
        global_variables.shop_type = Integer.parseInt(shop_type);
    } catch (IOException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }
like image 308
Deepak Avatar asked Jul 14 '11 16:07

Deepak


2 Answers

Use getClass().getResourceAsStream("foo.properties")

But note that using the default package is discouraged (the above will work with any package).

Your code doesn't work because the FileInputStream(..) uses paths relative to the current user directory (see java.io.File documentation). So it looks for foo.properties in /home/usr/ or c:\documents and settings\usr. Since your .properties file is on the classpath you can read it as such - throug the Class.getResourceAsStream(..) method.

like image 75
Bozho Avatar answered Sep 25 '22 13:09

Bozho


As others have indicated, you should load it from the classpath instead of as a file if you want to be able to load it from a jar. You want the Class.getResourceAsStream() method or the ClassLoader.getResourceAsStream() method. However, using getClass().getResourceAsStream("pos_config.properties") is dangerous because you're using a path that's resolved relative to the given class, and a subclass could change the location against which it's resolved. Therefore, it's safest to name an absolute path within the jar:

getClass().getResourceAsStream("/pos_config.properties")

or even better, use a class literal instead of getClass():

Foo.class.getResourceAsStream("pos_config.properties")
like image 25
Ryan Stewart Avatar answered Sep 23 '22 13:09

Ryan Stewart