Objective: To read the contents of the Mypro*.properties file separately, and review the method of reading the resource configuration file in the project.
Project: HTTP://PAN.BAIDU.COM/S/1C1GXKVM
Project structure, Readproperties.java is the main method for reading resource files:
Premise: When using InputStream to read, you need to pay attention to close the flow!!
Same Code section:
Properties Prop=new properties ();
InputStream Ins=null;
try{
INS ...//Code Changes Section
Prop.load (INS);
String resultstr=prop.getproperty ("param1");
}catch (Exception e) {
E.printstacktrace ();
}finally{
if (null!=ins) {
try{
Ins.close ();
}catch (IOException e) {
E.printstacktrace ();
}
}
}
Code Changes section:
1, read mypro1.properties, read and class files in the same directory resource file:
Ins=readproperties.class.getresourceasstream ("mypro1.properties");//Do not getclassloader () to get GetResourceAsStream () , which is to get the resource file under the same path
2. Read Mypro2.properties, read the resource file under another folder:
Ins=readproperties.class.getclassloader (). getResourceAsStream ("config/mypro2.properties");//The path where the resource file is written
3, read the mypro3.properties, read the src root directory of the resource files:
Ins=readproperties.class.getclassloader (). getResourceAsStream ("mypro3.properties");//write only the name of the resource file
4. Read Mypro4.properties, read the resource file under another resource bundle
Ins=readproperties.class.getclassloader (). getResourceAsStream ("mypro4.properties");//write file name only; if it is configfolder/ Mypro4.properties, a null exception is reported
5. Read Mypro5.properties, read the resource file under another package
Ins=readproperties.class.getclassloader (). getResourceAsStream ("com/test/mypro5.properties"); The path where the resource file resides, and if only the resource file name is written, the null exception is reported
Summarize:
1, Get and class files under the same path of the resource file using ReadProperties.class.getResourceAsStream ("Mypro1.properties") to obtain, not. Class.getclassloader ()
2. Get the configuration file under other packages or folders under different packages, using ReadProperties.class.getClassLoader (). getResourceAsStream ("Config/mypro2.properties") To get, the parameter is the relative path where the resource file resides
3. Obtain the resource file under the root directory of the SRC root directory or another resource folder, using ReadProperties.class.getClassLoader (). getResourceAsStream ("Mypro2.properties") Parameter writes only the resource file name.
If you have a better way, please do not hesitate to enlighten! ^_^
Java Foundation--properties Use