在项目中,经常会用到很多的工具类,比如读取配置文件,上传下载,导入导出,json解析,排序等一些工具类。以前用到了很多,但是没有记录,等到下次工作的时候,要么就是在网上找,要么就是问同事要。现在准备总结一下这些工具类,以后好用到。
Java读取配置文件一使用properties类读取:
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();
}
}
}
使用InputStreamReader流,主要是为了可以转换字符编码,以防乱码;
使用Spring去读取配置文件
<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>
在我们的VO层只需要通过注解就可以注入了;
@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}")