日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

Code片段 : .properties属性文件操作工具类 JSON工具类

發布時間:2025/4/5 javascript 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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工具类的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。