Configuration file
Placed under SRC obj.properties
Classname=com.store.order.dao.impl.orderdaoimpl
Way One
@Test Public void test1() throws exception{//files are placed under SRC. Eclipse will automatically copy one to the bin directory, or below the build/classes,InputStream is= Class.forName ("Com.store.test.test"). getClassLoader (). getResourceAsStream ("Obj.properties"); Properties Properties =NewProperties (); Properties.load ( is); String className = Properties.getproperty ("ClassName"); System. out. println (ClassName); }
Way Two
/** * Deprecated, file location is fixed, can only be used in this machine, we copy the class file to others can not use the * @throws Exception * * @Test Public void test2()throwsexception{FileInputStream FIS =NewFileInputStream ("D:\\workspaces\\store_v1.0\\src\\obj.properties"); Properties Properties =NewProperties (); Properties.load (FIS); String className = Properties.getproperty ("ClassName"); System.out.println (ClassName); }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
Mode three
@Test Public void test3()throwsexception{//Read config file, only read default suffix named properties (not written) //If there is a package, the notation is com.store.obj //detail: He can only read files under Classpath path, cannot writeResourceBundle bundle = Resourcebundle.getbundle ("obj"); String className = bundle.getstring ("ClassName");//Get value by keySystem.out.println (ClassName); }
Mode Four
/** * Spring provides propertiesloaderutils allows you to load a property resource directly from a file address based on a classpath * The greatest benefit is that the configuration file is loaded in real-time, it takes effect immediately after the modification, and does not have to restart */ Private Static void Springutil() {Properties props =NewProperties (); while(true){Try{Props=propertiesloaderutils.loadallproperties ("Message.properties"); for(Object Key:props.keySet ()) {System.out.print (key+":"); System.out.println (Props.get (key)); } }Catch(IOException e) {System.out.println (E.getmessage ()); }Try{Thread.Sleep ( the);}Catch(Interruptedexception e) {E.printstacktrace ();} } }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
Four common ways to read a configuration file in Java