Java工具類之配置檔案讀取
阿新 • • 發佈:2019-02-15
在專案中,經常會用到很多的工具類,比如讀取配置檔案,上傳下載,匯入匯出,json解析,排序等一些工具類。以前用到了很多,但是沒有記錄,等到下次工作的時候,要麼就是在網上找,要麼就是問同事要。現在準備總結一下這些工具類,以後好用到。
Java讀取配置檔案一使用properties類讀取:
使用InputStreamReader流,主要是為了可以轉換字元編碼,以防亂碼;public static Properties getProperty(String URL){ Properties properties = new Properties(); String path = System.getProperty("global.config.path") + URL; FileInputStream fileInputStream=null; try { fileInputStream=new FileInputStream(path); InputStreamReader is = new InputStreamReader(fileInputStream, "UTF-8"); properties.load(is); return properties; } catch (Exception e) { throw new RuntimeException( path + " is not exist."); }finally{ try { fileInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } }
使用Spring去讀取配置檔案
在我們的VO層只需要通過註解就可以注入了;<bean id="dcenterCommonPropertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="ignoreUnresolvablePlaceholders" value="true"/> <property name="fileEncoding" value="UTF-8" /> <property name="locations"> <list> <value>file:${global.config.path}/back-order/back-order-service/service.properties</value> <value>file:${global.config.path}/back-order/back-order-service/jobconfig.properties</value> </list> </property> </bean>
@Component("BackOrderLogisticsConfig") public class BackOrderLogisticsConfig { @Value("${kuaidi100.id}") private String id;// 註冊的key值 @Value("${kuaidi100.url}") private String url;// 註冊的url地址 @Value("${kuaidi100.show}") private String show;// 返回值型別 0:json,1:返回xml物件,2:返回html物件,3:返回text文字。 @Value("${kuaidi100.muti}") private String muti;// 返回的行數 @Value("${kuaidi100.order}")