【JAVA】properties配置文件
properties
是一种后缀为.properties的文本文件,在Java中常被用作配置文件,文件的内容格式是“键=值”的格式,可以用“#”作为注释
示例:存数据库的连接字符串
driver=com.mysql.jdbc.Driver jdbcUrl=jdbc:mysql://localhost:3306/user user=root password=123456
Properties类
- 存在于Java.util.Properties包下
- 是Java中用来处理properties文件的类
常用方法
-
setProperty(String key, String value) 调用 Hashtable 的方法 put。
-
store(OutputStream out, String comments)
以适合使用 load(InputStream) 方法加载到 Properties 表中的格式,将此 Properties 表中的属性列表(键和元素对)写入输出流。 -
store(Writer writer, String comments)
以适合使用 load(Reader) 方法的格式,将此 Properties 表中的属性列表(键和元素对)写入输出字符。
public class PropertiesTest { @Test public void propertiesTest(){ //实例化一个Properties对象 Properties pros = new Properties(); // try catch 异常处理 try { //写入文件 FileOutputStream fos = new FileOutputStream("test1.properties"); //引入Writer,明确写入配置文件的编码,避免中文乱码使用utf-8 OutputStreamWriter ops = new OutputStreamWriter(fos,"utf-8"); //将需要写入的属性内容通过setProperty方法,存入properties对象中 pros.setProperty("test","123"); //调用存储方法store pros.store(ops,"测试数据"); //关闭资源 ops.close(); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
- load(InputStream inStream) 从输入流中读取属性列表(键和元素对)。
- load(Reader reader) 按简单的面向行的格式从输入字符流中读取属性列表(键和元素对)
- getProperty(String key) 用指定的键在此属性列表中搜索属性
- getProperty(String key, String defaultValue) 用指定的键在属性列表中搜索属性。
public class getPropertiesTest { @Test public void propertiesTest(){ //读取文件 File file = new File("day04-02/src/hello.properties"); System.out.println(file.exists()); FileInputStream fis = new FileInputStream(file); //实例化Properties类 Properties p = new Properties(); // 读取列表 p.load(fis); //枚举器(Hashtable Vector) 迭代器 Enumeration<Object> keys = p.keys(); while (keys.hasMoreElements()){ String key = (String) keys.nextElement(); System.out.println(key + " = " + p.getProperty(key) ); } } }
- storeToXML(OutputStream os, String comment) 发出一个表示此表中包含的所有属性的 XML 文档。
- storeToXML(OutputStream os, String comment, String encoding)使用指定的编码发出一个表示此表中包含的所有属性的 XML 文档。
- loadFromXML(InputStream in) 将指定输入流中由 XML 文档所表示的所有属性加载到此属性表中。
-------------------------------------------------------------------------------------
如果万事开头难 那请结局一定圆满 @ Phoenixy
-------------------------------------------------------------------------------------
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南