Properties file isn't included in jar file when package Java application
I have developed Java desktop application using Netbeans. In my application, I used some properties files and I placed it under the Project folder so that I can access it by using code like that
Prop开发者_开发技巧erties props = new Properties();
props.load(new FileInputStream("config.properties"));
But when I deploy and package my application to .jar file, I can't find out where properties files are and my application can not read value from properties files.
How can I fix that bug, and where should I place my properties file and load it?
Put it under /src/resources/
, then use it like below.
ResourceBundle props = ResourceBundle.getBundle("resources.config");
NetBeans doesn't include the files under your project directory. Further, you need to build the project, in order to let NetBeans put the properties
file inside your /classes
directory. Then you should be able to pick it up, by running your application or just a particular related Java class.
Cheers.
I started with ralphie boy's solution and it didn't work. Well, it would have worked if I had done what he said. Here's what I did and maybe it will add some useful detail.
I have always named my packages after the project, so I was not aware that in NetBeans there is literally, a package named <default package>
. When I dragged my config.properties file up to the Source Packages level, low and behold a <default package>
was made. It got placed in the src folder and built at the root in the dist .jar file. After that, ralphie boy's solution was a cut and paste.
If you want your resource bundle or config file to be in the package, you have to include the path to it in the baseName string, like
ResourceBundle f = ResourceBundle.getBundle("pkgname/config");
or
ResourceBundle f = ResourceBundle.getBundle("com/mycompany/pkgname/config");
To include a properties file that exists in the classpath (i.e. if it is somewhere under your /src directory when you build the jar file), you can use getResourceAsStream() like this:
Properties properties = new Properties();
properties.load(this.getClass().getResourceAsStream("/config.properties"));
Note the leading slash on the filename. You can also use this to get to files within different packages in your project.
properties.load(this.getClass().getResourceAsStream("/com/company/project/config.properties"));
In your Java project, in the default package (i.e. .../src/), put this file: messages.properties
In your code, put this:
ResourceBundle f = ResourceBundle.getBundle("messages");
This approach has the charming aspect that it actually works!
(Someone edited and civilized my original post, which had a lot of SCREAM in it. I was seeing some pretty invalid answers getting votes, which I haven't seen for a long time on this site.)
精彩评论