Several ways that Java reads. properties files

Source: Internet
Author: User

In Java development, some of the variable configuration parameters need to be placed in the XML configuration file or in the properties configuration file. XML configuration files, however, need to be parsed by DOM or SAX, and it is easier to read the properties configuration file.

Describes several reading methods:

1. Read the configuration file based on Classloder

Note : This method can only read the configuration file under the Classpath, but it is limited if the configuration file is convenient under the classpath.

1     Properties Properties = new properties (); 2     //use ClassLoader to load the Properties configuration file to generate the corresponding input stream 3     inputstream in = PropertiesMain.class.getClassLoader (). getResourceAsStream ("Config/config.properties"); 4     // Use the Properties object to load the input stream 5     properties.load (in); 6     //Get key corresponding value 7     properties.getproperty (String key);

2. Read the configuration file based on InputStream

Note : The advantage of this approach is that you can read the configuration file under any path

1     Properties Properties = new properties (); 2     //use InputStream stream to read the Properties file 3     BufferedReader BufferedReader = new BufferedReader (New FileReader ("E:/config.properties")); 4     properties.load (BufferedReader); 5     //Get key corresponding to value 6     properties.getproperty (String key);

3, through the Java.util.ResourceBundle class to read, this way than the use of Properties to facilitate some

1> is obtained by means of the Resourcebundle.getbundle () static method (ResourceBundle is an abstract class), This way to get the Properties property file does not need to add. properties suffix name, only the file name can be

1 Properties.getproperty (String key), 2     //config is the property file name, placed under the package com.test.config, if it is placed under SRC, directly with config can  3     ResourceBundle resource = Resourcebundle.getbundle ("Com/test/config/config"); 4     

2> read from InputStream, get inputstream the same way as above, no longer repeat

1 ResourceBundle resource = new propertyResourceBundle (instream);

Note : The biggest problem encountered in the use of the configuration file may be the path problem, if the configuration file in the current class is located under the package, you need to use the Package name qualification, such as: Config.properties into the Com.test.config package, you want to use the Com/test/config/config.properties (through the properties to obtain) or com/test/config/ Config (obtained via resourcebundle); The attribute file is in the SRC root directory, then the Config.properties or config can be used directly.

Here are a few ways to test the code, for reference only:

  1 package com.test.properties;  2 3 Import Java.io.BufferedInputStream;  4 Import Java.io.File;  5 Import Java.io.FileInputStream;  6 Import java.io.IOException;  7 Import Java.io.InputStream;  8 Import java.util.Enumeration; 9 Import java.util.Properties; Ten import org.springframework.core.io.support.PropertiesLoaderUtils;   /** * @ClassName: Testproperties * @Description: Get profile information * @date: November 25, 2017 10:56:00 * @version: 1.0.0 * * public class Testproperties {/** * @Title: pri      Ntallproperty * @Description: Output All configuration information * @param props * @return void * @throws 30    */-private static void Printallproperty (Properties props) + @SuppressWarnings ("Rawtypes")   Enumeration en = Props.propertynames ();   The while (En.hasmoreelements ()) of the $ {PNS String key = (String) en.nextelement ();     38        String value = Props.getproperty (key);   SYSTEM.OUT.PRINTLN (key + ":" + value); 40} 41} 42 43/** 44 * Read value based on key * @Title: Getproperties_1 * @D                   Escription: The first way: based on the file name using the tool class in spring to parse the filepath is relative to the path, the file needs to be in the Classpath directory 49 *      For example: Config.properties under the package com.test.config, 50 * path is com/test/config/config.properties 51      * @param filePath * @param keyWord * @return * @return String 56  * @throws */FilePath public static string Getproperties_1 (string, string KeyWord) {Properties prop = null; String value = null; Propertiesloaderutils try {62//To get the Prop = Propertiesloaderutils.load through the spring's tools class Allproperties (FilePath); 64//search for the corresponding values according to the keyword. Value = Prop.getproperty (KeyWord);        66 } catch (IOException e) {e.printstacktrace (); 70} 71 72/** 73 * Read all information about the configuration file * * * @Title: Getproperties_1 * @Description: One way: Parse according to the file name using the tool class in spring * filepath is relative to the path, the file needs to be in the Classpath directory 78 * For example: con               Fig.properties under Package Com.test.config, 79 * path is com/test/config/config.properties 80 * Bayi * @param filePath getproperties_1 * @return void * @throws * * (String FilePath)             {prop = null; try {88]//Get 89 from the Propertiesloaderutils tool class in spring Prop = Propertiesloaderutils.loadallproperties (FilePath); Printallproperty (prop);      * catch (IOException e) {e.printstacktrace (); 93} 94} 95 96/** 97 * Read Value 98 * @Title: GETPR based on keyOperties_2 * @Description: The second way: Read the configuration file using the buffered input stream, then load it, then on Demand 101 * Absolute path or relative path, if it is a relative path, from when The directory under the previous item starts to calculate, 102 * For example: current project path/config/config.properties, 103 * relative path is CONFIG/CONFI G.properties 104 * @param filePath106 * @param keyWord107 * @return108 * @retur         N String 109 * @throws110 */111 public static string Getproperties_2 (String FilePath, String keyWord) {112 Properties prop = new properties (); 113 String value = null;114 try {115//read with input buffer stream             File InputStream InputStream = new Bufferedinputstream (new FileInputStream (new file (FilePath))); 117 Load input stream 118 prop.load (InputStream); 119//Get value values by keyword * * value = Prop.getpropert Y (KeyWord); 121} catch (Exception e) {122 e.printstacktrace (); 123}124 return value;12 5}126 127/**128 * Read configuration file All information 129 * @Title: Getproperties_2 131 * @Description: The second way: Read the configuration file using the buffered input stream and load it , then on Demand 132 * Absolute path or relative path, if it is relative path, then from the current project under the directory start calculation, 133 * such as: The current project path/config/config. Properties, 134 * Relative path is config/config.properties 135 * 136 * @param filePath13         7 * @return void138 * @throws139 */140 public static void Getproperties_2 (String filePath) {141 Properties prop = new properties (); 142 try {143//Read configuration file via input buffer stream 144 InputStream INPUTSTR EAM = new Bufferedinputstream (new FileInputStream (FilePath)); 145//Load Input stream 146 prop.load (I Nputstream); 147 printallproperty (prop); 148} catch (Exception e) {149 e.printstacktrace ();  150}151}152 153/**154 * Read from key value155 * 156 * @Title: Getproperties_3 157 * @Description: The Third Way: 158      * Relative path, the properties file needs to be in the Classpath directory, 159 * For example: Config.properties in Package com.test.co Nfig, 160 * path is/com/test/config/config.properties 161 * @param filePath162 * @param keyw ord163 * @return164 * @return String 165 * @throws166 */167 public static string Getproperties_3 (         String FilePath, String KeyWord) {168 Properties prop = new Properties (); 169 String value = null;170 try {171 InputStream InputStream = TestProperties.class.getResourceAsStream (filePath); 172 PROP.L Oad (InputStream); 173 value = Prop.getproperty (KeyWord); 174} catch (IOException e) {175 E.      Printstacktrace (); 176}177 return value;178}179 180/**181 * Read config file All information 182 * 183 * @Title: Getproperties_3 184 * @Description: The Third Way: 185 * Relative path, the properties file needs to be in the Classpath          Recorded, 186 *        For example: Config.properties under the package com.test.config, 187 * path is/com/test/config/config.properties 188 * @param filePath189 * @return190 * @throws191 */192 public static void Getproperties_3 (String Filepa Th) {193 Properties prop = new properties (); 194 try {195 InputStream InputStream = Testproperti         Es.class.getResourceAsStream (FilePath); 196 prop.load (InputStream); 197 Printallproperty (prop); 198 } catch (IOException e) {199 e.printstacktrace ();}201}202 203 204 Public S tatic void Main (string[] args) {205//Note path problem 206 String properties_1 = Getproperties_1 ("Com/test/config/co Nfig.properties "," Wechat_appid "); 207 System.out.println (" wechat_appid = "+ properties_1); 208 Getproperti Es_1 ("Com/test/config/config.properties"); 209 System.out.println ("********************************************* "); 210//Note path problem 211         String properties_2 = getproperties_2 ("Configure/configure.properties", "Jdbc.url"); 212 System.out.printl N ("Jdbc.url =" + properties_2); 213 getproperties_2 ("configure/configure.properties"); 214 System.out.print ln ("*********************************************"); 215//Note path problem 216 String Properties_3 = Getproperties_3 ("/com/test/config/config.properties", "Wechat_appid"); 217 System.out.println ("wechat_appid =" + Properties_3); 21 8 Getproperties_3 ("/com/test/config/config.properties"); 219}220}

Several ways that Java reads. properties files

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.