有时候我们希望处理properties文件,properties文件是键值对的文件形式,我们可以借助Properties类操作。

工具类如下:(代码中日志采用了slf4j日志)

package cn.xm.exam.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map.Entry;
import java.util.Properties; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; /**
* 操作properties文件的工具类(此工具类的file都是src目录下的properties文件,编译之后在build目录下)
*
* @author QiaoLiQiang
* @time 2018年11月3日下午12:05:32
*/
public class PropertiesFileUtils {
private static final Logger log = LoggerFactory.getLogger(PropertiesFileUtils.class); /**
* 构造函数私有化
*/
private PropertiesFileUtils() { } /**
* 保存或更新properties文件中的key
*
* @param fileName
* @param key
* @param value
*/
public static void saveOrUpdateProperty(String fileName, String key, String value) {
Properties properties = new Properties();
InputStream inputStream;
OutputStream outputStream;
try {
String path = ResourcesUtil.class.getClassLoader().getResource(fileName).getPath();
log.debug("path -> {}", path);
inputStream = new FileInputStream(new File(path));
properties.load(inputStream);
properties.setProperty(key, value); // 保存到文件中(如果有的话会自动更新,没有会创建)
outputStream = new FileOutputStream(new File(path));
properties.store(outputStream, ""); outputStream.close();
inputStream.close();
} catch (FileNotFoundException e) {
log.error("saveOrUpdateProperty error", e);
} catch (IOException e) {
log.error("saveOrUpdateProperty error", e);
}
} /**
* 获取Properties
*
* @param fileName
* @param key
* @return
*/
public static String getPropertyValue(String fileName, String key) {
Properties properties = new Properties();
InputStream inputStream;
String value = "";
try {
String path = PropertiesFileUtils.class.getClassLoader().getResource(fileName).getPath();
log.info("path -> {}", path);
inputStream = new FileInputStream(new File(path));
properties.load(inputStream); value = properties.getProperty(key);
// 保存到文件中(如果有的话会自动更新,没有会创建)
inputStream.close();
} catch (FileNotFoundException e) {
log.error("saveOrUpdateProperty error", e);
} catch (IOException e) {
log.error("saveOrUpdateProperty error", e);
}
return value;
} /**
* 获取Properties
*
* @param fileName
* @return
*/
public static Properties getProperties(String fileName) {
Properties properties = new Properties();
InputStream inputStream;
try {
String path = PropertiesFileUtils.class.getClassLoader().getResource(fileName).getPath();
log.info("path -> {}", path);
inputStream = new FileInputStream(new File(path));
properties.load(inputStream); inputStream.close();
} catch (FileNotFoundException e) {
log.error("saveOrUpdateProperty error", e);
} catch (IOException e) {
log.error("saveOrUpdateProperty error", e);
}
return properties;
} /**
* 获取Properties
*
* @param fileName
* @return
*/
public static Properties removeProperty(String fileName, String key) {
Properties properties = new Properties();
InputStream inputStream;
OutputStream outputStream;
try {
String path = PropertiesFileUtils.class.getClassLoader().getResource(fileName).getPath();
log.info("path -> {}", path);
inputStream = new FileInputStream(new File(path));
properties.load(inputStream);
log.info("properties -> {}", properties);
if (properties != null && properties.containsKey(key)) {
log.info("remove key:{}", key);
properties.remove(key);
} // 保存到文件中(将properties保存到文件)
outputStream = new FileOutputStream(new File(path));
properties.store(outputStream, ""); outputStream.close();
inputStream.close();
} catch (FileNotFoundException e) {
log.error("saveOrUpdateProperty error", e);
} catch (IOException e) {
log.error("saveOrUpdateProperty error", e);
}
return properties;
} public static void main(String[] args) {
// 保存三个 最后一个相当于更新
PropertiesFileUtils.saveOrUpdateProperty("settings.properties", "a", "aaa");
PropertiesFileUtils.saveOrUpdateProperty("settings.properties", "b", "bbb");
PropertiesFileUtils.saveOrUpdateProperty("settings.properties", "c", "ccc");
PropertiesFileUtils.saveOrUpdateProperty("settings.properties", "a", "AAA"); // 获取所有的properties
Properties properties = PropertiesFileUtils.getProperties("settings.properties");
System.out.println(properties); // 删除a
PropertiesFileUtils.removeProperty("settings.properties", "a"); // 获取所有的properties
Properties properties1 = PropertiesFileUtils.getProperties("settings.properties");
System.out.println(properties1);
} }

结果:

{b=bbb, a=AAA, c=ccc}
{b=bbb, c=ccc}

解释:

Properties是继承了HashTable的一个普通类,所以我们可以简单的认为操作Properties就是在操作HashTable。

public
class Properties extends Hashtable<Object,Object> { private static final long serialVersionUID = 4112578634029874840L; protected Properties defaults;
。。。
}

 由于HasTable键不可以重复,所以我们在saveOrUpdateProperty中直接setProperty的时候如果没有key会创建key,如果key存在会覆盖原来的值。

  properties.load(inputStream);是将properties文件中的key=value的数据加载到properties中;

  properties.store(outputStream, "");是将properties保存到一个文件中。

补充:上面代码还可以进一步将properties文件的位置封装全路径:

package cn.xm.exam.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; /**
*
* @author QiaoLiQiang
* @time 2018年11月3日下午12:05:32
*/
public class PropertiesFileUtils {
private static final Logger log = LoggerFactory.getLogger(PropertiesFileUtils.class); /**
* 构造函数私有化
*/
private PropertiesFileUtils() { } /**
* 保存或更新properties文件中的key
*
* @param fileName
* @param key
* @param value
*/
public static void saveOrUpdateProperty(String fileName, String key, String value) {
Properties properties = new Properties();
InputStream inputStream;
OutputStream outputStream;
try {
String path = ResourcesUtil.class.getClassLoader().getResource(fileName).getPath();
log.debug("path -> {}", path);
inputStream = new FileInputStream(new File(path));
properties.load(inputStream);
properties.setProperty(key, value); // 保存到文件中(如果有的话会自动更新,没有会创建)
outputStream = new FileOutputStream(new File(path));
properties.store(outputStream, ""); outputStream.close();
inputStream.close();
} catch (FileNotFoundException e) {
log.error("saveOrUpdateProperty error", e);
} catch (IOException e) {
log.error("saveOrUpdateProperty error", e);
}
} /**
* 获取Properties
*
* @param fileName
* @param key
* @return
*/
public static String getPropertyValue(String fileName, String key) {
Properties properties = new Properties();
InputStream inputStream;
String value = "";
try {
String path = PropertiesFileUtils.class.getClassLoader().getResource(fileName).getPath();
log.info("path -> {}", path);
inputStream = new FileInputStream(new File(path));
properties.load(inputStream); value = properties.getProperty(key);
// 保存到文件中(如果有的话会自动更新,没有会创建)
inputStream.close();
} catch (FileNotFoundException e) {
log.error("saveOrUpdateProperty error", e);
} catch (IOException e) {
log.error("saveOrUpdateProperty error", e);
}
return value;
} /**
* 获取Properties
*
* @param fileName
* @return
*/
public static Properties getProperties(String fileName) {
Properties properties = new Properties();
InputStream inputStream;
try {
String path = PropertiesFileUtils.class.getClassLoader().getResource(fileName).getPath();
log.info("path -> {}", path);
inputStream = new FileInputStream(new File(path));
properties.load(inputStream); inputStream.close();
} catch (FileNotFoundException e) {
log.error("saveOrUpdateProperty error", e);
} catch (IOException e) {
log.error("saveOrUpdateProperty error", e);
}
return properties;
} /**
* 获取Properties
*
* @param fileName
* @return
*/
public static Properties removeProperty(String fileName, String key) {
Properties properties = new Properties();
InputStream inputStream;
OutputStream outputStream;
try {
String path = PropertiesFileUtils.class.getClassLoader().getResource(fileName).getPath();
log.info("path -> {}", path);
inputStream = new FileInputStream(new File(path));
properties.load(inputStream);
log.info("properties -> {}", properties);
if (properties != null && properties.containsKey(key)) {
log.info("remove key:{}", key);
properties.remove(key);
} // 保存到文件中(将properties保存到文件)
outputStream = new FileOutputStream(new File(path));
properties.store(outputStream, ""); outputStream.close();
inputStream.close();
} catch (FileNotFoundException e) {
log.error("saveOrUpdateProperty error", e);
} catch (IOException e) {
log.error("saveOrUpdateProperty error", e);
}
return properties;
} /**
* 保存或更新properties文件中的key
*
* @param path
* 文件全路径
* @param key
* @param value
*/
public static void saveOrUpdatePropertyByFilePath(String path, String key, String value) {
Properties properties = new Properties();
InputStream inputStream;
OutputStream outputStream;
try {
log.debug("path -> {}", path);
inputStream = new FileInputStream(new File(path));
properties.load(inputStream);
properties.setProperty(key, value); // 保存到文件中(如果有的话会自动更新,没有会创建)
outputStream = new FileOutputStream(new File(path));
properties.store(outputStream, ""); outputStream.close();
inputStream.close();
} catch (FileNotFoundException e) {
log.error("saveOrUpdateProperty error", e);
} catch (IOException e) {
log.error("saveOrUpdateProperty error", e);
}
} /**
* 获取Properties
*
* @param path
* 文件全路径
* @param key
* @return
*/
public static String getPropertyValueByFilePath(String path, String key) {
Properties properties = new Properties();
InputStream inputStream;
String value = "";
try {
log.info("path -> {}", path);
inputStream = new FileInputStream(new File(path));
properties.load(inputStream); value = properties.getProperty(key);
// 保存到文件中(如果有的话会自动更新,没有会创建)
inputStream.close();
} catch (FileNotFoundException e) {
log.error("saveOrUpdateProperty error", e);
} catch (IOException e) {
log.error("saveOrUpdateProperty error", e);
}
return value;
} /**
* 获取Properties
*
* @param path
* 文件全路径
* @return
*/
public static Properties getPropertiesByFilePath(String path) {
Properties properties = new Properties();
InputStream inputStream;
try {
log.info("path -> {}", path);
inputStream = new FileInputStream(new File(path));
properties.load(inputStream); inputStream.close();
} catch (FileNotFoundException e) {
log.error("saveOrUpdateProperty error", e);
} catch (IOException e) {
log.error("saveOrUpdateProperty error", e);
}
return properties;
} /**
* 获取Properties
*
* @param path
* 文件全路径
* @param key
* key值
* @return
*/
public static Properties removePropertyByFilePath(String path, String key) {
Properties properties = new Properties();
InputStream inputStream;
OutputStream outputStream;
try {
log.info("path -> {}", path);
inputStream = new FileInputStream(new File(path));
properties.load(inputStream);
log.info("properties -> {}", properties);
if (properties != null && properties.containsKey(key)) {
log.info("remove key:{}", key);
properties.remove(key);
} // 保存到文件中(将properties保存到文件)
outputStream = new FileOutputStream(new File(path));
properties.store(outputStream, ""); outputStream.close();
inputStream.close();
} catch (FileNotFoundException e) {
log.error("saveOrUpdateProperty error", e);
} catch (IOException e) {
log.error("saveOrUpdateProperty error", e);
}
return properties;
}
}

补充:如果是spring项目读取jar包中的配置可以用 ClassPathResource 进行读取:

    /**
* 获取文件中对应的key的名称
*
* @param fileName
* @param key
* @return
*/
public static String getPropertyValue(String fileName, String key) {
Properties properties = new Properties();
InputStream inputStream = null;
String value = ""; try {
ClassPathResource resource = new ClassPathResource(fileName);
inputStream = resource.getInputStream();
properties.load(inputStream);
value = properties.getProperty(key);
} catch (Exception e) {
log.error("saveOrUpdateProperty error", e);
} finally {
IOUtils.closeQuietly(inputStream);
} return value;
}

补充:由于springboot打成jar包之后里面的文件不能实时修改,所以在当前程序的主目录下创建一settings.properties文件进行操作

package cn.qs.utils.system;

import java.io.File;
import java.io.IOException;
import java.util.Date; import javax.servlet.http.HttpServletRequest; import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.SystemUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes; import cn.qs.bean.user.User;
import cn.qs.utils.UUIDUtils;
import cn.qs.utils.file.PropertiesFileUtils; public class MySystemUtils { private static final Logger LOGGER = LoggerFactory.getLogger(MySystemUtils.class); static {
checkSettingPropertyFiles();
} private MySystemUtils() {
} /**
* 检查settings.properties文件是否存在,不存在就创建
*/
public static void checkSettingPropertyFiles() {
File userDir = SystemUtils.getUserDir();
File propertiesFile = new File(userDir, "settings.properties");
if (!propertiesFile.exists()) {
try {
propertiesFile.createNewFile();
LOGGER.info("create settings.properties success, path: {}", propertiesFile.getAbsolutePath());
} catch (IOException e) {
LOGGER.error("create settings.properties failed", e);
}
}
} public static final String settings_file_path = SystemUtils.getUserDir().getAbsolutePath() + "/settings.properties"; public static String getProductName() {
return getProperty("productName", "管理网");
} public static String getProperty(String key) {
return getProperty(key, "");
} public static String getProperty(String key, String defaultValue) {
return StringUtils.defaultIfBlank(PropertiesFileUtils.getPropertyValueByFilePath(settings_file_path, key),
defaultValue);
} public static void setProperty(String key, Object value) {
PropertiesFileUtils.saveOrUpdatePropertyByFilePath(settings_file_path, key, String.valueOf(value));
} }

  SystemUtils.getUserDir()方法获取的是项目所在的路径,如果是springboot打的jar包是jar包所在的目录。

Properties文件工具类的使用--获取所有的键值、删除键、更新键等操作的更多相关文章

  1. Property工具类,Properties文件工具类,PropertiesUtils工具类

    Property工具类,Properties文件工具类,PropertiesUtils工具类 >>>>>>>>>>>>>& ...

  2. Java读取properties文件工具类并解决控制台中文乱码

    1.建立properts文件(error.message.properties) HTTP201= 请求成功并且服务器创建了新的资源 2.在spring-mvc.xml文件(applicationCo ...

  3. 读取Properties文件工具类

    import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java ...

  4. 加载Properties文件工具类:LoadConfig

    import javax.servlet.http.HttpServletRequest; import javax.ws.rs.GET; import javax.ws.rs.Path; impor ...

  5. 我的Java开发学习之旅------>工具类:Java获取字符串和文件进行MD5值

    ps:这几天本人用百度云盘秒传了几部大片到云盘上,几个G的文件瞬秒竟然显示"上传成功"!这真让我目瞪口呆,要是这样的话,那得多快的网速,这绝对是不可能的,也许这仅是个假象.百度了一 ...

  6. 读取Config文件工具类 PropertiesConfig.java

    package com.util; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io ...

  7. Android FileUtil(android文件工具类)

    android开发和Java开发差不了多少,也会有许多相同的功能.像本文提到的文件存储,在Java项目和android项目里面用到都是相同的.只是android开发的一些路径做了相应的处理. 下面就是 ...

  8. Java常用工具类---IP工具类、File文件工具类

    package com.jarvis.base.util; import java.io.IOException;import java.io.InputStreamReader;import jav ...

  9. java下载文件工具类

    java下载文件工具类 package com.skjd.util; import java.io.BufferedInputStream; import java.io.BufferedOutput ...

随机推荐

  1. 最大获利 HYSBZ - 1497 (最大权闭合图)

    最大权闭合图: 有向图,每个点有点权,点权可正可负.对于任意一条有向边i和j,选择了点i就必须选择点j,你需要选择一些点使得得到权值最大. 解决方法: 网络流 对于任意点i,如果i权值为正,s向i连容 ...

  2. hdu 4348 To the moon (主席树 区间更新)

    链接: http://acm.hdu.edu.cn/showproblem.php?pid=4348 题意: 4种操作: C l r c   区间[l,r]加c,时间+1 Q l r    询问当前时 ...

  3. java BigDecimal加减乘除 与 保留两位小数

    BigDecimal bignum1 = new BigDecimal("10"); BigDecimal bignum2 = new BigDecimal("5&quo ...

  4. [luogu3505][bzoj2088][POI2010]TEL-Teleportation【分层图】

    题目大意 给出了一个图,然后让你加最多的边,让点\(1\)到\(2\)之间至少要经过5条边 解法 比较清楚,我们可以将这个图看作一个分层图,点\(1\)为第一层,再将\(2\)作为第五层,这样第一层和 ...

  5. Linux下的定时器类实现(select定时+线程)

    更好的计时器类实现:LINUX RTC机制实现计时器类(原创) 很多时候需要在LINUX下用到定时器,但像setitimer()和alarm()这样的定时器有时会和sleep()函数发生冲突,这样就给 ...

  6. BellmanFord 最短路

    时间复杂度:O(VE) 最多循环V次,每次循环对每一条边(共E条边)判断是否可以进行松弛操作 最多V次:一个点的最短路,最多包含V-1个点(不包含该点), 如d1->d2->d3-> ...

  7. Linux网络基本网络配置

    Linux网络基本网络配置方法介绍 网络信息查看 设置网络地址: cat /etc/sysconfig/network-scripts/ifcfg-eth0 你将会看到: DEVICE=eth0 BO ...

  8. zoj 3195(LCA加强版)

    传送门:Problem 3195 https://www.cnblogs.com/violet-acmer/p/9686774.html 题意: 给一个无根树,有q个询问,每个询问3个点(a,b,c) ...

  9. 洛谷P2148 [SDOI2009]E&D(博弈论)

    洛谷题目传送门 先安利蒟蒻仍在施工的博弈论总结 首先根据题目,石子被两两分组了,于是根据SG定理,我们只要求出每一组的SG值再全部异或起来就好啦. 把每一对数看成一个ICG,首先,我们尝试构造游戏的状 ...

  10. ajax上传文件及进度显示

    之前在博文:原生ajax写法就提及过ajax2.0与1.0的差别是多了FormData和利用FormData文件上传(当然还有跨域,但不是本文的重点). 那么具体怎么样实现ajax上传文件呢? 一般来 ...