Java method to read the properties file
- 2020-04-01 03:53:10
- OfStack
This article illustrates how Java can read the properties file. Share with you for your reference. The specific implementation method is as follows:
package com.test.demo;
import java.util.Properties;
import java.io.InputStream;
import java.io.IOException;
public final class TestProperties {
private static String param1;
private static String param2;
private static String param3;
private static String param4;
/**
* For the pathnames of the configuration files above, there is a problem that is easy to ignore,
* That's when you use Object.class.getClassLoader().get... The time,
* You don't have to add" / ",
* But don't getClassLoader(). I can't. What's the reason?
* Because this configuration file is placed in the project src , in object When you load it, you add" / ".
* If you want to copy this configuration file to the same package as the class, you don't need to add,
* If the configuration file is read in the following way:
*/
static {
Properties prop = new Properties();
//InputStream in = Object.class.getResourceAsStream("/test.properties");
//The file is under SRC
//InputStream in = TestProperties.class.getClassLoader().getResourceAsStream("jdbc.properties");
//The file is under SRC
InputStream in = TestProperties.class.getResourceAsStream("jdbc.properties");
//The files are in the same package
try {
prop.load(in);
param1 = prop.getProperty("mysql.driverClassName").trim();
param2 = prop.getProperty("mysql.url").trim();
param3 = prop.getProperty("mysql.username").trim();
param4 = prop.getProperty("mysql.password").trim();
} catch (IOException e) {
e.printStackTrace();
}
}
private TestProperties() {
}
public static String getParam1() {
return param1;
}
public static String getParam2() {
return param2;
}
public static String getParam3() {
return param3;
}
public static String getParam4() {
return param4;
}
public static void main(String args[]){
System.out.println(getParam1());
System.out.println(getParam2());
System.out.println(getParam3());
System.out.println(getParam4());
}
}
I hope this article has been helpful to your Java programming.