Sometimes, write a configuration file, you need to know what to read it is right, we need to test, to see what we want to read is not the same. A tool class is written to read the contents of the configuration file.
1. Create a new Java project, import the required jar packages, and create a new configuration file such as:
2. Contents of the configuration file:
1 Driver=com.mysql.jdbc.driver 2 url=jdbc:mysql://localhost:3306/csdn 3 User=root 4 pwd=123456 5 initsize=1 6 maxactive=1 7 maxwait=5000 8 maxidle=1 9 minidle=1
3. Read the configuration file tool class:
1 PackageCom.cnblogs.daliu_it;2 3 ImportJava.io.FileInputStream;4 Importjava.util.Properties;5 6 /**7 * Read configuration file8 * @authorDaliu_it9 */Ten Public classGetProperties { One Public Static voidgetProperties () { A Try { - //java.util.Properties - /* the * Properties class for reading properties files use this class to read the contents of a configuration file in a map-like format - * - * Content format in the properties file is similar: User=openlab then the equals sign is key, and the right side of the equals sign is value. - */ +Properties prop =NewProperties (); - + /* A * Use properties to read configuration files at */ -FileInputStream FIS =NewFileInputStream ("Config.properties"); - /* - * When the file is read through the properties, then the stream remains open and we should close it on our own. - */ - prop.load (FIS); in fis.close (); -System.out.println ("Successfully loaded complete profile"); to + /* - * When loading is complete, you can get the content (value) to the right of the equal sign based on the content (key) of the equal sign in the text file. the * The properties can be seen as a map in disguise * */ $String Driver = prop.getproperty ("Driver"). Trim ();Panax NotoginsengString url = prop.getproperty ("url"). Trim (); -String user = Prop.getproperty ("User"). Trim (); theString pwd = Prop.getproperty ("pwd"). Trim (); +System.out.println ("Driver:" +driver); ASystem.out.println ("URL:" +URL); theSystem.out.println ("User:" +user); +System.out.println ("pwd:" +pwd); - $}Catch(Exception e) { $ e.printstacktrace (); - } - } the}
4. Test class:
1 Packagecom.daliu_it.test;2 3 Importjava.sql.SQLException;4 5 Importorg.junit.Test;6 7 ImportCom.cnblogs.daliu_it. GetProperties;8 9 Public classTestCase {Ten One /** A * Get configuration files - * @throwsSQLException - */ the @Test - Public voidTestgetproperties ()throwsSQLException { -GetProperties poperties=NewGetProperties (); - poperties.getproperties (); + } -}
5.:
Original Daliu_it
Blog Source: http://www.cnblogs.com/liuhongfeng/p/4176224.html
The copyright of this article is owned by the author and the blog Park, but reproduced without the consent of the author must retain the above statement and placed in the article page obvious location. Thank you for your cooperation.
Use properties to read configuration files and get specific content values