Scenarios that you might encounter during programming:
Fetching data from a file (config file, etc.) multiple times, but the configured file is in the form of a string, the obtained value is also a string type, which requires you to manually convert it to the desired type, if the number of times is not a big problem, if the number of reads frequently, think of how many times the same code will be used, Cause the code to be large and redundant.
At this point, we usually need to write our own tool classes and encapsulate similar code (methods, etc.) that we often use.
Take data from the properties file here for example.
The first data taken from the file may be a file name, you may need to get an integer or floating-point type value, or you may get a date data, which requires that the extracted withered string data be removed and converted to the desired type. So in this custom tool Class I inherited the following method:
String getString (String key)//Get normal string or file
Date getDate (String key)//Get a Date data (default format)
Date getDate (String key,string format)//Get a Date data (custom format)
Double getdouble (String key)//Get a floating-point data
Package Cn.jamsbwo.util;import Java.io.file;import Java.io.fileinputstream;import java.io.ioexception;import Java.text.parseexception;import java.text.simpledateformat;import Java.util.date;import java.util.Properties;/** * Integrated reading of the contents of the properties file * Read Normal string * Read file name * read-shaped, float * Read Date type * The profile name must be config.properties * @author Administrator * */publi C class Configutil {private static Properties Config=new properties ();p rivate configutil () {}public static properties GetC Onfig () {return config;} Static{try {config.load (new FileInputStream (New File ("Config.properties"));} catch (IOException e) { E.printstacktrace ();}} /** take string */public static string getString (String key) {return Config.getproperty (key);} /** take integer */public static int getInt (String key) {return Integer.parseint (Config.getproperty (key));} /** take floating point number double*/public static double getdouble (String key) {return double.parsedouble (key);} /** Date (custom format) */public static date getDate (String key,string format) {date date=null; SimpledateformaT sdf=new simpledateformat (format); String Datestr=config.getproperty (key); try {date=sdf.parse (DATESTR);} catch (ParseException e) {e.printstacktrace ();} return date;} /** Fetch Date (default 1994-02-28) */public static date getDate (String key) {return getDate (key, "YYYY-MM-DD");}}
Custom tool Classes