當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
Code片段 : .properties属性文件操作工具类 JSON工具类
生活随笔
收集整理的這篇文章主要介紹了
Code片段 : .properties属性文件操作工具类 JSON工具类
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
摘要: 原創出處:www.bysocket.com 泥瓦匠BYSocket 希望轉載,保留摘要,謝謝! “貴專”?— 泥瓦匠
一、java.util.Properties API & 案例
java.util.Properties 是一個屬性集合。常見的api有如下:
- load(InputStream inStream) ?從輸入流中讀取屬性
- getProperty(String key) ?根據key,獲取屬性值
- getOrDefault(Object key, V defaultValue)?根據key對象,獲取屬性值需要強轉
首先在resources目錄下增加/main/resources/fast.properties:
fast.framework.name=fast fast.framework.author=bysocket fast.framework.age=1然后直接上代碼PropertyUtil.java:
/*** .properties屬性文件操作工具類** Created by bysocket on 16/7/19.*/ public class PropertyUtil {private static final Logger LOGGER = LoggerFactory.getLogger(PropertyUtil.class);/** .properties屬性文件名后綴 */public static final String PROPERTY_FILE_SUFFIX = ".properties";/*** 根據屬性文件名,獲取屬性** @param propsFileName* @return*/public static Properties getProperties(String propsFileName) {if (StringUtils.isEmpty(propsFileName))throw new IllegalArgumentException();Properties properties = new Properties();InputStream inputStream = null;try {try {/** 加入文件名后綴 */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("加載屬性文件出錯!",e);throw new RuntimeException(e);}return properties;}/*** 根據key,獲取屬性值** @param properties* @param key* @return*/public static String getString(Properties properties, String key){return properties.getProperty(key);}/*** 根據key,獲取屬性值** @param properties* @param key* @param defaultValue* @return*/public static String getStringOrDefault(Properties properties, String key, String defaultValue){return properties.getProperty(key,defaultValue);}/*** 根據key,獲取屬性值** @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);} }UT如下:
/*** {@link PropertyUtil} 測試用例* <p/>* Created by bysocket on 16/7/19.*/ public class PropertyUtilTest {@Testpublic void testGetProperties() {Properties properties = PropertyUtil.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());}@Testpublic 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);}@Testpublic 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:
1 10 fast bysocket 1 10 fast bysocket相關對應代碼分享在 Github 主頁
二、JACKSON 案例
首先,加個Maven 依賴:
<!-- 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>? 然后直接上代碼JSONUtil:
/*** JSON 工具類* <p/>* Created by bysocket on 16/7/19.*/ public class JSONUtil {private static final Logger LOGGER = LoggerFactory.getLogger(JSONUtil.class);/*** 默認JSON類**/private static final ObjectMapper mapper = new ObjectMapper();/*** 將 Java 對象轉換為 JSON 字符串** @param object* @param <T>* @return*/public static <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;}/*** 將 JSON 字符串轉化為 Java 對象** @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;}}UT如下:
/*** {@link JSONUtil} 測試用例* <p/>* Created by bysocket on 16/7/19.*/ public class JSONUtilTest {@Testpublic void testToJSONString() {JSONObject jsonObject = new JSONObject(1, "bysocket", 33);String jsonStr = JSONUtil.toJSONString(jsonObject);Assert.assertEquals("{\"age\":1,\"name\":\"bysocket\",\"id\":33}", jsonStr);}@Test(expected = RuntimeException.class)public void testToJSONStringError() {JSONUtil.toJSONString(System.out);}@Testpublic 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}", JSONObject.class);} }class JSONObject {int age;String name;Integer id;public JSONObject() {}public JSONObject(int age, String name, Integer id) {this.age = age;this.name = name;this.id = id;}public int getAge() {return age;}public void setAge(int age) {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;}@Overridepublic String toString() {return "JSONObject{" +"age=" + age +", name='" + name + '\'' +", id=" + id +'}';} }Run Console(拋出了異常信息):
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!三、小結
相關對應代碼分享在 Github 主頁 請看到的Java小伙伴多交流多評論改進之。 參考 黃勇 smart
如以上文章或鏈接對你有幫助的話,別忘了在文章結尾處評論哈~ 你也可以點擊頁面右邊“分享”懸浮按鈕哦,讓更多的人閱讀這篇文章。
總結
以上是生活随笔為你收集整理的Code片段 : .properties属性文件操作工具类 JSON工具类的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [转]ASP.NET中使用UpdateP
- 下一篇: [Java 安全]加密算法