Configuration files are indispensable in the application system and can be addedProgram
Flexibility. java. util. properties is a class from jdk1.2 and supports Load
() Method. After jdk1.4, save (output, string) is changed to store (output, string)
Read configuration files
,
XX. properties in the webroot/WEB-INF/classes/directory
First, you can convert the configuration file to inputstream in either of the following two ways:
(1) inputstream = thread. currentthread (). getcontextclassloader (). getresourceasstream ("XX. properties ");
(2)
Inputstream =
This. getclass ()
. Getclassloader (). getresourceasstream (
"XX. properties"
);
The getclass () method of the called object is to obtain the current class type of the object, which is stored in the method area,
Then, call
The getclassloader () method gets the class loader of the current type. We know that all classes in Java are loaded to the virtual machine through the loader, and there is a parent between the class loaders.
The child relationship means that the child knows the parent and the parent does not know the child. In this way, different types of child loading cannot be accessed (although they are all placed in the method area ), so here we use the loader of the current class to load resources.
Is to ensure that it is loaded with the same loader as the class type.
Finally, the getresourceasstream () method of the Class Loader is called to load resources.
Load the configuration file and read the property value.
Properties prop = new properties ();
Prop. Load (input );
String value = prop. getproperty ("propertyname ");
Input. Close ();
Modify the configuration file:
Strign filename ="
XX. Properties
";
Inputstream = NULL;
Fileoutputstream outputstream = NULL;
Properties P = new properties ();
Try {
Inputstream = This. getclass (). getclassloader (). getresourceasstream (filename );
// The input stream must be obtained through the absolute path.
String Path = pagecontext. getservletcontext (). getrealpath ("/") +
WEB-INF/classes/
;
// Or string Path = This. getclass (). getclassloader (). getresource ("/"). getpath ()
;
Outputstream = new fileoutputstream (path + filename );
P. load (inputstream);
P. setproperty (propertyname, value ). tostring ();
P. store (outputstream, "Description");
}catch (filenotfoundexception E2) {
e2.printstacktrace ();
}catch (ioexception E) {
E. printstacktrace ();
}finally {
inputstream. close ();
outputstream. close ();
}< br>