Code snippet:. Properties Property File Operations Tool Class & JSON tool class

Source: Internet
Author: User

Absrtact: Original creation Place: www.bysocket.com Mason bysocket Hope reprint, keep abstract, thank you! "Your Special"-Masons

First, java.util.Properties API & Case

Java.util.Properties is a collection of properties. The common APIs are as follows:

    • Load (InputStream instream) reads a property from the input stream
    • GetProperty (String key), based on key, gets the property value
    • Getordefault (Object key, V defaultvalue) depending on the key object, getting the property value requires a strong turn

First add/main/resources/fast.properties under the resources directory:

Fast.framework.name=fastfast.framework.author=bysocketfast.framework.age=1

Then directly on the code Propertyutil.java:

/** *. Properties Property File Operation Tool Class * * Created by Bysocket on 16/7/19.    */public class Propertyutil {private static final Logger Logger = Loggerfactory.getlogger (Propertyutil.class);    /**. Properties Property filename suffix */public static final String property_file_suffix= ". Properties"; /** * Based on the property filename, Get Properties * * @param propsfilename * @return */public static properties GetProperties (STR        ing Propsfilename) {if (Stringutils.isempty (propsfilename)) throw new IllegalArgumentException ();        Properties Properties = new properties ();        InputStream inputstream = null;  try {try {/** add filename suffix */if (Propsfilename.lastindexof (property_file_suffix) = =                -1) {propsfilename + = Property_file_suffix; } InputStream = Thread.CurrentThread (). Getcontextclassloader (). getResourceAsStream (                Propsfilename);        if (null! = InputStream)            Properties.load (InputStream);                } finally {if (null! = InputStream) {inputstream.close ();            }}} catch (IOException e) {logger.error ("Error loading property file!", e);        throw new RuntimeException (e);    } return properties; }/** * Based on key, get property value * * @param properties * @param key * @return */public static String get    String (Properties Properties, string key) {return Properties.getproperty (key);    }/** * Based on key, gets the property value * * @param properties * @param key * @param defaultvalue * @return * * public static string Getstringordefault (properties properties, string key, String defaultvalue) {return propertie    S.getproperty (Key,defaultvalue);      }/** * Based on key, get property value * * @param properties * @param key * @param defaultvalue * @param <V> * @return */public static <V> V GetorDefault (Properties Properties, String key, V DefaultValue) {return (v) properties.getordefault (key,defaultvalue); }}

The

UT is as follows:

/** * {@link propertyutil} test Case * <p/> * Created by Bysocket on 16/7/19. */public class Propertyutiltest {@Test public void testgetproperties () {Properties properties = Propertyuti        L.getproperties ("fast");        String fastframeworkname = Properties.getproperty ("Fast.framework.name");        String AuthorName = Properties.getproperty ("Fast.framework.author");        Object age = Properties.getordefault ("Fast.framework.age", 10);        Object defaultval = Properties.getordefault ("Fast.framework.null", 10);        System.out.println (Fastframeworkname);        System.out.println (AuthorName);        System.out.println (Age.tostring ());    System.out.println (Defaultval.tostring ());        } @Test public void Testgetstring () {Properties Properties = propertyutil.getproperties ("Fast");        String fastframeworkname = propertyutil.getstring (Properties, "Fast.framework.name"); String AuthorName = propertyutil.getstring (Properties, "Fast.framework.author");        System.out.println (Fastframeworkname);    System.out.println (AuthorName);        } @Test public void Testgetordefault () {Properties Properties = propertyutil.getproperties ("Fast");        Object age = Propertyutil.getordefault (Properties, "Fast.framework.age", 10);        Object defaultval = Propertyutil.getordefault (Properties, "Fast.framework.null", 10);        System.out.println (Age.tostring ());    System.out.println (Defaultval.tostring ()); }}

Run Console:

110fastbysocket110fastbysocket

Related code Share on Github homepage

Ii. The case of JACKSON

First, add a maven dependency:

                                <!--Jackson--><dependency><groupid>org.codehaus.jackson</groupid><artifactid> Jackson-mapper-asl</artifactid><version>1.9.13</version></dependency><dependency ><groupId>org.codehaus.jackson</groupId><artifactId>jackson-jaxrs</artifactId>< Version>1.9.13</version></dependency>

Then directly on the code jsonutil:

/** * JSON Tool class * <p/> * Created by Bysocket on 16/7/19.    */public class Jsonutil {private static final Logger Logger = Loggerfactory.getlogger (Jsonutil.class);    /** * Default JSON class **/private static final Objectmapper mapper = new Objectmapper (); /** * Convert a Java object to a JSON string * * @param object * @param <T> * @return */public static &LT ;        T> string tojsonstring (T object) {string jsonstr;        try {jsonstr = Mapper.writevalueasstring (object);            } catch (Exception e) {logger.error ("Java Object Can ' t covert to JSON string!");        throw new RuntimeException (e);    } return JSONSTR; /** * Convert JSON string to Java Object * * @param JSON * @param clazz * @param <T> * @return *        /public static <T> T Toobject (String JSON, class<t> clazz) {T object;        try {object = Mapper.readvalue (JSON, clazz); } catch (ExceptiOn e) {logger.error ("JSON String Can ' t covert to Java object!");        throw new RuntimeException (e);    } return object; }}

The

UT is as follows:

/** * {@link jsonutil} test Case * <p/> * Created by Bysocket on 16/7/19. */public class Jsonutiltest {@Test public void testtojsonstring () {Jsonobject jsonobject = new Jsonobject (1        , "Bysocket", 33);        String jsonstr = jsonutil.tojsonstring (Jsonobject);    Assert.assertequals ("{\" age\ ": 1,\" name\ ": \" bysocket\ ", \" id\ ":"), JSONSTR); } @Test (expected = runtimeexception.class) public void Testtojsonstringerror () {jsonutil.tojsonstring (System    . out);        } @Test public void Testtoobject () {Jsonobject jsonobject = new Jsonobject (1, "Bysocket", 33);        String jsonstr = jsonutil.tojsonstring (Jsonobject);        Jsonobject resultobject = Jsonutil.toobject (Jsonstr, Jsonobject.class);    Assert.assertequals (Jsonobject.tostring (), resultobject.tostring ()); } @Test (expected = runtimeexception.class) public void Testtoobjecterror () {Jsonutil.toobject ("{int:1}", JSO    Nobject.class);    }}class jsonobject {int age; String name;    Integer ID;        Public Jsonobject () {} public Jsonobject (int., String name, Integer id) {this.age = age;        THIS.name = name;    This.id = ID;    } public int Getage () {return age;    public void Setage (int.) {this.age = age;    } public String GetName () {return name;    } public void SetName (String name) {this.name = name;    } public Integer GetId () {return id;    } public void SetId (Integer id) {this.id = ID;  } @Override Public String toString () {return ' jsonobject{' + ' age= ' + Age + ',    Name= ' + name + ' \ ' + ', id= ' + ID + '} '; }}

Run Console (Exception information thrown):

16/07/19 23:09:13 ERROR util. Jsonutil:json String Can ' t covert to Java OBJECT!16/07/19 23:09:13 ERROR util. Jsonutil:java Object Can ' t covert to JSON string!
Third, summary

related code Share on the Github homepage Please see the Java Small partner multi-communication multi-comment improvement. Reference Huang Yong Smart

If the above article or link is helpful to you, don't forget to comment at the end of the article AH ~ You can also click on the right side of the page " share " hover button Oh, let more people read this article.

Code snippet:. Properties Property File Operations Tool Class & JSON tool class

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.