Packagecom. LY;ImportJava.io.BufferedInputStream;ImportJava.io.FileInputStream;ImportJava.io.FileOutputStream;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.OutputStream;Importjava.util.Enumeration;Importjava.util.Properties; Public classTestmain {//read value by key Public Staticstring ReadValue (String FilePath, String key) {Properties props=NewProperties (); Try{InputStream in=NewBufferedinputstream (NewFileInputStream (FilePath)); Props.load (in); String value=Props.getproperty (key); SYSTEM.OUT.PRINTLN (Key+value); returnvalue; } Catch(Exception e) {e.printstacktrace (); return NULL; }}//Read all information about the properties Public Static voidreadproperties (String filePath) {Properties props=NewProperties (); Try{InputStream in=NewBufferedinputstream (NewFileInputStream (FilePath)); Props.load (in); Enumeration en=Props.propertynames (); while(En.hasmoreelements ()) {String key=(String) en.nextelement (); String Property=Props.getproperty (key); SYSTEM.OUT.PRINTLN (Key+Property ); }}Catch(Exception e) {e.printstacktrace (); }}//Write properties Information Public Static voidwriteproperties (String FilePath, String parametername, String parametervalue) {Properties prop=NewProperties (); Try{InputStream fis=NewFileInputStream (FilePath); //read the list of attributes from the input stream (key and element pairs) prop.load (FIS); //Call the Hashtable method put. Use the GetProperty method to provide parallelism. //enforces the use of strings for the keys and values of the properties. The return value is the result of the Hashtable call put. OutputStream fos =NewFileOutputStream (FilePath); Prop.setproperty (ParameterName, ParameterValue); //In a format that is appropriate for loading into the properties table using the Load method,//writes the list of attributes (key and element pairs) in this properties table to the output streamProp.store (FOS, "Update" + parametername+ "' Value"); } Catch(IOException e) {System.err.println ("Visit" + FilePath + "for updating" + parametername + "Value error"); }} Public Static voidMain (string[] args) {ReadValue ("Info.properties", "url"); WriteProperties ("Info.properties", "Age", "22"); ReadProperties ("Info.properties"); System.out.println ("OK"); }}
Code to read and write properties files in Java