Java读取properties文件

本文介绍了一个使用Java进行Properties配置文件的读写操作示例,包括普通格式与XML格式的Properties文件处理方法。通过示例代码展示了如何创建、读取及修改Properties文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;

public class TestProperties {
    public static void main(String[] args) throws IOException {
        setProperties("test.properties");
        readProperties("test.properties");
        setXMLProperties("test.properties");
        readXMLProperties("test.properties");
    }
    public static void readProperties(String filename) throws IOException {
        // 实例化Properties对象
        Properties info = new Properties();
        // 初始文件输入流
        InputStream in = new FileInputStream(filename);
        // 从输入流中读取属性列表
        info.load(in);
        // 获取属性
        String username = info.getProperty("username");
        String password = info.getProperty("password");
        System.out.printf("username:%s password:%s\n", username, password);
        in.close();
    }
    public static void setProperties(String filename) throws IOException {
        // 实例化Properties对象
        Properties info = new Properties();
        // 初始文件输出流
        OutputStream out = new FileOutputStream(filename);
        // 设置属性
        info.setProperty("username", "zp");
        info.setProperty("password", "1314");
        // 写入输出流
        info.store(out, "commt");
        out.close();
    }
    public static void setXMLProperties(String filename) throws IOException {
        Properties info = new Properties();
        OutputStream out = new FileOutputStream(filename);
        info.setProperty("username", "zp");
        info.setProperty("password", "1314");

        // 写入输出流
        info.storeToXML(out, "commt");

        out.close();
    }
    public static void readXMLProperties(String filename) throws IOException {
        Properties info = new Properties();
        InputStream in = new FileInputStream(filename);

        // 从XML中读取属性列表
        info.loadFromXML(in);

        String username = info.getProperty("username");
        String password = info.getProperty("password");
        System.out.printf("username:%s password:%s\n", username, password);
        in.close();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值