Properties文件操作

简介: Properties文件操作

Properties文件读取与写入:

properties,主要用于读取java配置文件,各种语言都有自己所支持的配置文件,配置文件中很多变量是经常改变的,这样做也是为了方便用户,用用户能够脱离程序本身去修改相关的变量设置。

它提供了几个主要的方法:

getProperty(String key)用指定的键在此属性列表中搜索属性,也就是通过参数key,得到key所对应的value,

setProperty(String key, String value)调用HashTable的方法put。他通过基类的put方法来设置键值对。

store(OutputStream out,String comments)以适合使用load方法加载到Properties表中的格式,将次Properties表中的属性列表(键和元素对)写入输出流,与load方法相反,该方法将键值对写入到指定的文件中

load(InputStream in)从输入流中读取属性列表(键和元素对)。通过对指定文件Properties进行装载来获取该文件中的所有键值对,以供getProperty来搜索。

代码演示:

config.properties文件

username = root
password = root

读取操作:

public class Test13 {
    private static String username;
    private static String password;
    public static void main(String[] args) {
        readConfig();
    }
    private static void readConfig() {
        Properties p = new Properties();
        try {
            InputStream inputStream = new FileInputStream("E:\\idea_workspace3\\yangli\\class_obj\\src\\com\\lili\\file\\config.properties");
            p.load(inputStream);//加载文件
            username = p.getProperty
                    ("username");
            password = p.getProperty("password");
            System.out.println(username);
            System.out.println(password);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

写入操作:

public class Test13 {
    public static void main(String[] args) {
        writeConfig("nibi", "444");
    }
    /**
     * 写入到配置文件
     */
    private static void writeConfig(String username, String password) {
        Properties p = new Properties();
        p.put("USERNAME", username);
        p.setProperty("password", password);
        try {
            OutputStream outputStream = new FileOutputStream("E:\\idea_workspace3\\yangli\\class_obj\\src\\com\\lili\\file\\config.properties");
            // 写文件
            p.store(outputStream, "更新");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


目录
相关文章
|
2天前
|
监控 网络协议 算法
2026年起SSL证书有效期逐年缩短:企业如何避免“续期风暴”!
SSL证书有效期将从2026年起分三阶段逐步缩短至47天,人工续期难以为继。阿里云“WoSign SSL证书+自动化服务”,支持域名监控、自动托管、云产品/服务器一键部署及智能提醒,助力企业高效应对高频续期挑战。
8072 2
|
11天前
|
域名解析 人工智能 Linux
|
19天前
|
人工智能
Google 提示「所在地区不可用」?进不去 Antigravity 或 Gemini,先查账号这个设置
进不去 Antigravity 或 Gemini,提示所在地区不可用?三步查清 Google 账号关联地区、官方更正表单理由选法与改区注意事项。
10182 13
Google 提示「所在地区不可用」?进不去 Antigravity 或 Gemini,先查账号这个设置
|
5天前
|
人工智能 安全 网络安全
|
10天前
|
Linux API iOS开发
【DSH】DeepSeek Harness新手保姆教程(下载+安装+配置+使用,2026最新实测)
DeepSeek Harness(dsh)是 DeepSeek AI 开源的智能体框架,秉持“一切皆插件”理念,支持读文件、改代码、执行命令、处理表格等自动化任务;免费开源,兼容 Win/macOS,需配 API 密钥使用。(239字)
1531 5
|
9天前
|
云安全 数据采集 人工智能
|
16天前
|
人工智能 开发工具 开发者
2026最新codex下载安装保姆级使用教程(下载+安装+登录+使用,含所有历史版本)
Codex 是 OpenAI 推出的开源 AI 编程智能体,跑在本地终端和桌面客户端里,能读懂整个代码仓库,一句自然语言就能让它改代码、执行命令、跑测试、修 Bug,支持 Windows、macOS、Linux 三大平台。本文把 Codex下载、安装、登录、汉化、基础使用一次讲全,并整理了国内用户最常踩的坑,跟着做 10 分钟就能跑起来。
2689 8