java-properties文件读取工具类(代码片段)

wang1001 wang1001     2023-01-06     519

关键词:

  1 import org.apache.commons.configuration.ConfigurationException;
  2 import org.apache.commons.configuration.PropertiesConfiguration;
  3 
  4 import com.alibaba.fastjson.JSON;
  5 import com.alibaba.fastjson.JSONObject;
  6 
  7 /**
  8  * @ClassName: ReadPropertiesUtil
  9  */
 10 public class ReadPropertiesUtil 
 11     // 声明配置文件
 12     private static String[] confProps =  "config.properties" ;
 13     private static PropertiesConfiguration conf = null;
 14 
 15     /**
 16      * 获取所有配置对象
 17      */
 18     public static PropertiesConfiguration getConf() 
 19         conf = new PropertiesConfiguration();// 初始化对象
 20         /* 把所有props配置文件一次加载,共后续使用 */
 21         for (int i = 0; i < confProps.length; i++) 
 22             try 
 23                 conf.load(confProps[i]);
 24              catch (ConfigurationException e) 
 25                 conf = null;
 26             
 27         
 28         return conf;
 29     
 30 
 31     /*
 32      * PropsUtil getInt()
 33      */
 34     public static Integer getInt(String key) 
 35         /** 声明返回值 **/
 36         Integer value = null;
 37         try 
 38             /* 获取value值 */
 39             conf = getConf();
 40             value = conf.getInt(key);
 41          catch (Exception e) 
 42         
 43         return value;
 44     
 45 
 46     /*
 47      * PropsUtil getString()
 48      */
 49     public static String getString(String key) 
 50         /** 声明返回值 **/
 51         String value = null;
 52         try 
 53             /* 获取value值 */
 54             conf = getConf();
 55             value = conf.getString(key);
 56          catch (Exception e) 
 57         
 58         return value;
 59     
 60 
 61     /*
 62      * PropsUtil getLong()
 63      */
 64     public static Long getLong(String key) 
 65         /** 声明返回值 **/
 66         Long value = null;
 67         try 
 68             /* 获取value值 */
 69             conf = getConf();
 70             value = conf.getLong(key);
 71          catch (Exception e) 
 72         
 73         return value;
 74     
 75 
 76     /*
 77      * PropsUtil getBoolean()
 78      */
 79     public static boolean getBoolean(String key) 
 80         /** 声明返回值 **/
 81         boolean value = true;
 82         try 
 83             /* 获取value值 */
 84             conf = getConf();
 85             value = conf.getBoolean(key);
 86          catch (Exception e) 
 87             value = false;
 88         
 89         return value;
 90     
 91 
 92     /*
 93      * PropsUtil getList()
 94      */
 95     public static String[] getStringArray(String key) 
 96         /** 声明返回值 **/
 97         String[] value = null;
 98         try 
 99             /* 获取value值 */
100             conf = getConf();
101             value = conf.getStringArray(key);
102          catch (Exception e) 
103         
104         return value;
105     
106 
107     /*
108      * PropsUtil getJsonHeaders()
109      */
110     public static JSONObject getJsonHeaders(String key) 
111         JSONObject json = null;// 声明返回值
112         try 
113             /** 解析*.Properties文件 **/
114             conf = getConf();
115             String value = conf.getString(key).replace("=", ",");
116             json = JSON.parseObject(value);
117          catch (Exception e) 
118         
119         return json;
120     
121 
122     public static void main(String[] args) throws Exception 
123 
124         System.out.println(getString("dbcp.url"));
125 
126         // String[] tmp = getStringArray("Email_to");
127         // for(String to:tmp)
128         // System.out.println(to);
129         // 
130 
131         // JSONObject json = getJsonHeaders("httpHead");
132         // for(Entry<String, Object> entry:json.entrySet())
133         // System.out.println(entry.getKey() + "-----" + entry.getValue().toString());
134         // 
135 
136         // System.out.println(getInt("dbcp.url"));
137 
138         // System.out.println(getInt("redis.minIdle"));
139         // String[] tmp = getStringArray("redis.redisSlaveIp");
140         // for(int i=0;i<tmp.length;i++)
141         // System.out.println(tmp[i].split(":")[0]);
142         // System.out.println(tmp[i].split(":")[1]);
143         // 
144     
145 
 1 //相关依赖
 2         <!-- commons-configuration -->
 3         <dependency>
 4             <groupId>commons-configuration</groupId>
 5             <artifactId>commons-configuration</artifactId>
 6             <version>1.9</version>
 7         </dependency>
 8         <!-- fastjson json -->
 9         <dependency>
10             <groupId>com.alibaba</groupId>
11             <artifactId>fastjson</artifactId>
12             <version>1.2.7</version>
13         </dependency>

 Properties文件载入工具类:

  依赖spring等。

  

 1         <dependency>
 2             <groupId>org.slf4j</groupId>
 3             <artifactId>slf4j-api</artifactId>
 4             <version>1.7.7</version>
 5         </dependency>
 6         <dependency>
 7             <groupId>org.slf4j</groupId>
 8             <artifactId>slf4j-log4j12</artifactId>
 9             <version>1.7.7</version>
10         </dependency>

 

  1 import java.io.IOException;
  2 import java.io.InputStream;
  3 import java.util.NoSuchElementException;
  4 import java.util.Properties;
  5 
  6 import org.apache.commons.io.IOUtils;
  7 import org.slf4j.Logger;
  8 import org.slf4j.LoggerFactory;
  9 import org.springframework.core.io.DefaultResourceLoader;
 10 import org.springframework.core.io.Resource;
 11 import org.springframework.core.io.ResourceLoader;
 12 
 13 /**
 14  * Properties文件载入工具类. 可载入多个properties文件,
 15  * 相同的属性在最后载入的文件中的值将会覆盖之前的值,但以System的Property优先.
 16  */
 17 public class PropertiesLoader 
 18     private static Logger logger = LoggerFactory.getLogger(PropertiesLoader.class);
 19     private static ResourceLoader resourceLoader = new DefaultResourceLoader();
 20     private final Properties properties;
 21 
 22     public PropertiesLoader(String... resourcesPaths) 
 23         properties = loadProperties(resourcesPaths);
 24     
 25     
 26     public Properties getProperties() 
 27         return properties;
 28     
 29 
 30     /**
 31      * 取出Boolean类型的Property,但以System的Property优先.如果都为Null抛出异常,如果内容不是true/false则返回false.
 32      */
 33     public Boolean getBoolean(String key) 
 34         String value = getValue(key);
 35         if (value == null) 
 36             throw new NoSuchElementException();
 37         
 38         return Boolean.valueOf(value);
 39     
 40 
 41     /**
 42      * 取出Boolean类型的Property,但以System的Property优先.如果都为Null则返回Default值,如果内容不为true/false则返回false.
 43      */
 44     public Boolean getBoolean(String key, boolean defaultValue) 
 45         String value = getValue(key);
 46         return value != null ? Boolean.valueOf(value) : defaultValue;
 47     
 48 
 49     /**
 50      * 取出Double类型的Property,但以System的Property优先.如果都为Null或内容错误则抛出异常.
 51      */
 52     public Double getDouble(String key) 
 53         String value = getValue(key);
 54         if (value == null) 
 55             throw new NoSuchElementException();
 56         
 57         return Double.valueOf(value);
 58     
 59 
 60     /**
 61      * 取出Double类型的Property,但以System的Property优先.如果都为Null则返回Default值,如果内容错误则抛出异常
 62      */
 63     public Double getDouble(String key, Integer defaultValue) 
 64         String value = getValue(key);
 65         return value != null ? Double.valueOf(value) : defaultValue;
 66     
 67 
 68     /**
 69      * 取出Integer类型的Property,但以System的Property优先.如果都为Null或内容错误则抛出异常.
 70      */
 71     public Integer getInteger(String key) 
 72         String value = getValue(key);
 73         if (value == null) 
 74             throw new NoSuchElementException();
 75         
 76         return Integer.valueOf(value);
 77     
 78 
 79     /**
 80      * 取出Integer类型的Property,但以System的Property优先.如果都为Null则返回Default值,如果内容错误则抛出异常
 81      */
 82     public Integer getInteger(String key, Integer defaultValue) 
 83         String value = getValue(key);
 84         return value != null ? Integer.valueOf(value) : defaultValue;
 85     
 86 
 87     /**
 88      * 取出String类型的Property,但以System的Property优先,如果都为Null则抛出异常.
 89      */
 90     public String getProperty(String key) 
 91         String value = getValue(key);
 92         if (value == null) 
 93             throw new NoSuchElementException();
 94         
 95         return value;
 96     
 97 
 98     /**
 99      * 取出String类型的Property,但以System的Property优先.如果都为Null则返回Default值.
100      */
101     public String getProperty(String key, String defaultValue) 
102         String value = getValue(key);
103         return value != null ? value : defaultValue;
104     
105 
106     /**
107      * 取出Property,但以System的Property优先,取不到返回空字符串.
108      */
109     private String getValue(String key) 
110         String systemProperty = System.getProperty(key);
111         if (systemProperty != null) 
112             return systemProperty;
113         
114         if (properties.containsKey(key)) 
115             return properties.getProperty(key);
116         
117         return "";
118     
119 
120     /**
121      * 载入多个文件, 文件路径使用Spring Resource格式.
122      */
123     private Properties loadProperties(String... resourcesPaths) 
124         Properties props = new Properties();
125         for (String location : resourcesPaths) 
126             InputStream is = null;
127             try 
128                 Resource resource = resourceLoader.getResource(location);
129                 is = resource.getInputStream();
130                 props.load(is);
131              catch (IOException ex) 
132                 logger.info("Could not load properties from path:" + location + ", " + ex.getMessage());
133              finally 
134                 IOUtils.closeQuietly(is);
135             
136         
137         return props;
138     
139 

 

csvfileutil读取写入csv文件简单工具类(代码片段)

参考github大神源码总结一下最简单的工具类记录一下/***@descriptionCSV文件读取和输出工具类.<br/>*@authormichael*@date2019/05/16*@versionCopyright(c)2019,[email protected]AllRightsReserved.*/publicclassCSVFileUtilprivatesta 查看详情

java常用工具类——文件读取的操作类(代码片段)

定义常用的文件类型publicclassFileType/***文件头类型*/publicstaticfinalStringXML_FILE="text/xml;charset=UTF-8";publicstaticfinalStringPDF_FILE="application/pdf";publicstaticfinalStringPDG_FILE="application/x-png";p 查看详情

properties文件读取工具类(代码片段)

...止硬编码,经常会将一些与业务相关的数据存在properties文件中,根据不同的key加载不同的数据,所以就会有读取properties文件的东西,这篇文章仅为了以后copy方便写的。1.添加依赖:<!--https://mvnrepository.com/artifact/commons-configurati... 查看详情

java读取.txt文件工具类fileutiles(代码片段)

publicclassFileUtilsprivatestaticfinalStringENCODING="UTF-8";//编码方式/***获取文件的行**@paramfileName*文件名称*@returnList<String>*/publicstaticStringgetContentByLine(StringfileName)StringBufferlines=newS 查看详情

9hutool实战:fileutil文件工具类(读取文件)(代码片段)

...xff08;带你掌握里面的各种工具)目录用途:FileUtil文件工具类(读取文件)使用场景读取文件内容的各种骚操作项目引用此博文的依据:hutool-5.6.5版本源码<dep 查看详情

配置文件读取工具类--propertiesutil(代码片段)

...shMap<String,Object>();//静态块中加载static//读取多个配置文件init("b.properties");//类路径下直接使用文件名,文件加载方式要全路径名//init("fileName2");//读取配置文件操作privatestaticvoidinit(StringfileName)trypro=newProperties();//文件方式//pro.l... 查看详情

c#.net工具类一excel读取与写入(代码片段)

...据:1  publicpartialclassExcelFile23///<summary>4///读取Excel文件5///</s 查看详情

15友盟项目--资源文件工具类(resourceutil)sql执行工具类(execsqlutil)(代码片段)

资源文件工具类把sql脚本转换为String字符串--->交给sql工具类ExecSQLUtil执行sql1.资源文件工具类(ResourceUtil)  把sql脚本转换为String字符串/***资源文件工具类*/publicclassResourceUtil/***以String方式读取整个资源串*/publicstaticStringreadResou... 查看详情

基于python封装读取ini文件的工具类python+requests库做接口自动化框架设计系列多测师(代码片段)

...ny:上海多测师信息有限公司===========================""""""配置文件类的封装封装的目的:使用更简单封装的需求:1、简化创建配置文件解析器对象,加载配置文件的流程(需要 查看详情

java常用的16个工具类(代码片段)

...够,则失败二.org.apache.commons.io.FileUtilsdeleteDirectory:删除文件夹readFileToString:以字符形式读取文件内容deleteQueitly:删除文件或文件夹且不会抛出异常copyFile:复制文件writeStringToFile:把字符写到目标文件,如果文件不存在,则创... 查看详情

每期一个小窍门:简单文件摘要工具类(代码片段)

有时候我们程序内部要进行文件传输,为了安全考虑,需要摘要校验.比如想传递文件A,获取了文件A的摘要a,对方在读取此文件时,用同样的摘要算法算出a的话就证明文件A没有被篡改,反之就是被篡改了(摘要码不匹配)下方是工具类的... 查看详情

每期一个小窍门:简单文件摘要工具类(代码片段)

有时候我们程序内部要进行文件传输,为了安全考虑,需要摘要校验.比如想传递文件A,获取了文件A的摘要a,对方在读取此文件时,用同样的摘要算法算出a的话就证明文件A没有被篡改,反之就是被篡改了(摘要码不匹配)下方是工具类的... 查看详情

1.javapoi读取写入excel(包括样式)的工具类utils(代码片段)

...yExcel来实现功能,很简单方便;而对于复杂的excel文件,如有各式各样的合并单元格、表头不固定、行列跟随业务数据动态变化……格式变幻多端的文件,easyExcel就显得无能为力了,选择poi就可以解决此问题了... 查看详情

excel工业级读取工具类(代码片段)

最近在做一个自动化匹配快速导入功能,对excel表格导入的一些问题发一个工业级的读取发工具类importorg.apache.poi.ss.usermodel.*;importorg.apache.poi.ss.util.CellRangeAddress;importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;importjava.i 查看详情

mendmix代码解析:百搭的配置文件读取工具resourceutils(代码片段)

...久以前当微服务还没出现、配置中心还没出现、yaml配置文件也还没流行的时候,我们都习惯在项目里面写一个类似ResourceUtils或者PropertiesUtil的工具,无论在静态方法还是jsp代码都屡试不爽。如今Springcloud各种参数化配置... 查看详情

java工具类beanutils库介绍以及对象拷贝(代码片段)

...属性数据封装到对象中。我们在开发中经常会从各种配置文件中读取相应的数据,需要明白的一点是从配置文件中读取到的数据都是String,但是很显然我们的应用程序中不仅仅有String一种数据类型,比如: 查看详情

java读取资源文件(resourcesfile)(代码片段)

Java读取资源文件(resourcesfile)使用springboot自带的工具类即可。importorg.springframework.util.ResourceUtils;比如我们要获取箭头所指文件:Filefile=ResourceUtils.getFile("classpath:lginfo/cppinfo.json");这样就可以获取到了。关于 查看详情

游戏场景需要是可配置的:assetmanager工具类和xml文件读取(代码片段)

...每次加个地图就要改一次代码,太麻烦了。我们选择用xml文件来做配置(PS,有条件的可以用服务器和数据库存储,这个我们另外再说)。fight_scene.xml大致如下:<?xmlversion="1.0"encoding="utf-8"?><resources><fight_sceneid="1"><... 查看详情