Read the properties file in the Java project

  • 2020-05-26 08:31:48
  • OfStack

The following 1-4 are related knowledge collected on the Internet. To sum up, they are as follows:

1. The most common method for reading properties files is InputStream in = getClass().getResourceAsStream(" resource Name"); This requires that the properties file and the current class be in the same folder. If in a different package, you must use:


InputStream ins = this.getClass().getResourceAsStream("/cn/zhao/properties/testPropertiesPath2.properties");

2. Get the path method in Java

3. Get a simple implementation of the path

4. Three ways to get properties files by reflection

1. Reflection method: the most common way to obtain properties files and thinking:

There are many ways for Java to read properties files. The most popular article on the Internet is "6 ways for Java to read properties files". However, in the application of Java, getResourceAsStream(String name) method of java.lang.Class is most commonly used.


InputStream in = getClass().getResourceAsStream(" resources Name");

The problem with this is that the getClass() call omits this! As we all know, this cannot be used in static (static) methods or static blocks, because methods or code blocks of type static belong to the class itself, not to an object, while this itself represents the current object, while static methods or blocks are called without initializing the object.

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

So what do you do? In fact, this class is not used in this way, it just needs to get 1 Class object, that is not easy
Take the parent of all the classes, Object, Object.class, isn't it easier and safer than what you're doing with the class you're writing? Well, here is an example to facilitate communication.


import java.util.Properties;  
import java.io.InputStream;  
import java.io.IOException;  
 
/**  
*  read Properties Examples of files   
* File: TestProperties.java  
* User: leizhimin  
* Date: 2008-2-15 18:38:40  
*/   
public  final  class TestProperties {  
   private  static String param1;  
   private  static String param2;  
 
   static {  
    Properties prop = new Properties();  
    InputStream in = Object. class .getResourceAsStream( "/test.properties" );  
     try {  
      prop.load(in);  
      param1 = prop.getProperty( "initYears1" ).trim();  
      param2 = prop.getProperty( "initYears2" ).trim();  
    } catch (IOException e) {  
      e.printStackTrace();  
    }  
  }  
 
   /**  
   *  Private constructor that does not need to create an object   
   */   
   private TestProperties() {  
  }  
 
   public  static String getParam1() {  
     return param1;  
  }  
 
   public  static String getParam2() {  
     return param2;  
  }  
 
   public  static  void main(String args[]){  
    System.out.println(getParam1());  
    System.out.println(getParam2());  
  }  
}  

Operation results:

151
152

Of course, replace Object.class with int.class.

In addition, if the static method or block reads the Properties file, there is another safe way to get the Class object directly by the name of the class itself, such as TestProperties.class in this case. This is the safest way to do this

2 ways to get the path:


File fileB = new File( this .getClass().getResource( "" ).getPath()); 
System. out .println( "fileB path: " + fileB);  

2.2 get the project name of the current class:


System. out .println("user.dir path: " + System. getProperty ("user.dir"))

Get a simple Java implementation of the path


/** 
 
   * Gets the absolute path to the file under the relative path of the project  
 
   * 
 
   * @param parentDir 
 
   * The parent directory of the target file , For example, , Project directory , There are lib with bin and conf directory , So the program runs at lib or 
 
   * bin, Then the required configuration file is conf inside , You need to find the absolute path to the configuration file  
 
   * @param fileName 
 
   * The file name  
 
   * @return1 Two absolute paths  
 
   */ 
 
  public static String getPath(String parentDir, String fileName) { 
 
    String path = null; 
 
    String userdir = System.getProperty("user.dir"); 
 
    String userdirName = new File(userdir).getName(); 
 
    if (userdirName.equalsIgnoreCase("lib") 
 
        || userdirName.equalsIgnoreCase("bin")) { 
 
      File newf = new File(userdir); 
 
      File newp = new File(newf.getParent()); 
 
      if (fileName.trim().equals("")) { 
 
        path = newp.getPath() + File.separator + parentDir; 
 
      } else { 
 
        path = newp.getPath() + File.separator + parentDir 
 
            + File.separator + fileName; 
 
      } 
 
    } else { 
 
      if (fileName.trim().equals("")) { 
 
        path = userdir + File.separator + parentDir; 
 
      } else { 
 
        path = userdir + File.separator + parentDir + File.separator 
 
            + fileName;  
      } 
 
    } 
     return path; 
 
  } 

4. Get the path by means of reflection:


InputStream ips1 = Enumeration . class .getClassLoader() .getResourceAsStream( "cn/zhao/enumStudy/testPropertiesPath1.properties" ); 
InputStream ips2 = Enumeration . class .getResourceAsStream( "testPropertiesPath1.properties" ); 
InputStream ips3 = Enumeration . class .getResourceAsStream( "properties/testPropertiesPath2.properties" ); 

Related articles: