Some of the information in the Java project, such as the configuration information for the Web, may be placed in the. properties file, so how do we read them, the following gives a tool class to do a description, and solve the problem of Chinese garbled:
1, wherein the Config.properties file information is as follows:
Name=\u843d\u82b1\u6709\u610fwang Wang Str=\u6d41\u6c34\u65e0\u60c5boolean=true
2. Propertiesutil tool class read. properties file
Import Java.io.bufferedinputstream;import Java.io.bufferedreader;import Java.io.fileinputstream;import Java.io.ioexception;import Java.io.inputstream;import Java.io.inputstreamreader;import java.util.Properties; public class Propertiesutil {private static String default_properties = "Config.properties"; private static Properties prop; static {prop = new Properties (); try {InputStream is = new Bufferedinputstream (New FileInputStream (GetPath () + default_properties)); BufferedReader bf = new BufferedReader (new InputStreamReader (IS, "UTF-8"));//solve the problem of reading the characters in the properties file prop. Load (BF); } catch (Exception e) {e.printstacktrace (); }} public static string GetProperty (String key) {return Prop.getproperty (key); public static string GetProperty (string key, String defaultvalue) {String value = Prop.getproperty (key); if (value = = null) return defaultvalue; RetUrn value; The public static Boolean Getbooleanproperty (string name, Boolean defaultvalue) {String value = Prop.getproperty ( name); if (value = = null) return defaultvalue; Return (new Boolean (value)). Booleanvalue (); public static int Getintproperty (String name) {return Getintproperty (name, 0); public static int Getintproperty (string name, int defaultvalue) {String value = Prop.getproperty (name); if (value = = null) return defaultvalue; Return (new Integer). Intvalue (); The public static String GetPath () {return Thread.CurrentThread (). Getcontextclassloader (). GetResource (""). GetPath (); /** * Reads the value in the specified properties * @param properties FileName * @param Name property to read * @return */Private St Ring Readproper (String properties, string name) {InputStream InputStream = This.getclass (). getClassLoader (). getres Ourceasstream (properties); Properties p = new PropeRties (); try {p.load (InputStream); } catch (IOException E1) {e1.printstacktrace (); } return P.getproperty (name); } public static void Main (string[] args) {Propertiesutil propertiesutil = new Propertiesutil (); String name = Propertiesutil.getproperty ("name"); String str = propertiesutil.readproper ("config.properties", "str"); Boolean bo = Propertiesutil.getbooleanproperty ("boolean", false); System.out.println ("name==" +name+ "," + "str==" +str+ ", Boolean = =" +bo "); }}
Java read. Properties file and solve Chinese garbled problem