How to read the properties configuration file: properties configuration file
In general, the information about database connections is configured in the. properties file. We need to read the information from it to establish a connection with the database.
File directory:
Application. properties configuration information:
url=jdbc:oracle:thin:@localhost:orldriverName=oracle.jdbc.driver.OracleDriver username=scott password=tiger
We need to read the configuration information in application. properties in the java file:
1. getResourceAsStream obtains the resource file, loads the resource file using the load method, and obtains the Properties class.
Package com. xuhui; import java. io. IOException; import java. io. inputStream; import java. util. properties; public class MainApp {public static void main (String [] args) {Properties properties = new Properties (); InputStream in = MainApp. class. getResourceAsStream ("/application. properties "); // load application. properties resource file. If the file is in the package, add the package name try {properties. load (in); in. close ();} catch (IOException e) {// TODO Auto-generated catch block e. printStackTrace ();} System. out. print (properties. getProperty ("driverName"); // get application. driverName information in properties }}
2. getBundle in ResourceBundle obtains the resource file.
Package com. xuhui; import java. util. resourceBundle; public class MainApp {public static void main (String [] args) {ResourceBundle bundle = ResourceBundle. getBundle ("application"); // read application. properties file, without adding. properties suffix, without the path name System. out. print (bundle. getString ("driverName"); // get resource file information }}