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();
        }
    }
}

posted @   JamieChyi  阅读(10)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示