Read the properties file in the Java project

The contents in 1-4 below are the relevant knowledge collected online. To sum up, they are the following knowledge points:

1. The most common method to read the properties file is InputStream in = getclass() Getresourceasstream ("resource name"); This method requires the properties file and the current class to be in the same folder. If in different packages, you must use:

2. Get path method in Java

3. A simple implementation of obtaining path

4. There are three ways to obtain the properties file by reflection

1. The most common methods and thoughts of obtaining properties files by reflection:

There are many ways for Java to read properties files. The most popular article on the Internet is "six ways for Java to read properties files", but in Java applications, the most commonly used is through Java The getresourceasstream (string name) method of lang. class class, but I have seen many codes reading the properties file do this:

There is a problem, that is, this is omitted by default when calling getclass()! As we all know, this cannot be used in static methods or static blocks. The reason is that static methods or code blocks belong to the class itself and do not belong to an object. This itself represents the current object, and the object does not need to be initialized when static methods or blocks are called.

The problem is: if I don't want a class to have objects, I will make the default constructor of this class private, and of course I won't write other common constructors. And my class is a tool class, which is static methods and variables. If I want to obtain the properties file in a static block or static method, this method will not work.

Then what shall I do? In fact, this class is not used like this. It just needs to get a class object. It's not easy -- take the parent class object of all classes and use object Isn't class more convenient and safe than the class you're writing? Hehe, here is an example to facilitate communication.

Operation results:

151 152

Of course, put the object Replace class with int.class. Oh, you can try.

In addition, if the static method or block is used to read the properties file, another safest method is to directly obtain the class object by the name of the class itself. For example, in this example, it can be written as testproperties Class, this is the safest way

2. Method of obtaining path:

2.2 get the project name of the current class:

3 a simple java implementation of obtaining path

4. Obtain the path by reflection:

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>