Java怎么读写Properties配置文件

   2025-02-04 7600
核心提示:在Java中,可以使用java.util.Properties类来读写Properties配置文件。下面是一个简单的示例:读取配置文件:import java.io.Fil

在Java中,可以使用java.util.Properties类来读写Properties配置文件。下面是一个简单的示例:

读取配置文件:

import java.io.FileInputStream;import java.io.IOException;import java.util.Properties;public class PropertiesExample {    public static void main(String[] args) {        Properties properties = new Properties();        try {            // 加载配置文件            FileInputStream fileInputStream = new FileInputStream("config.properties");            properties.load(fileInputStream);            fileInputStream.close();            // 读取配置项            String username = properties.getProperty("username");            String password = properties.getProperty("password");            System.out.println("Username: " + username);            System.out.println("Password: " + password);        } catch (IOException e) {            e.printStackTrace();        }    }}

写入配置文件:

import java.io.FileOutputStream;import java.io.IOException;import java.util.Properties;public class PropertiesExample {    public static void main(String[] args) {        Properties properties = new Properties();        try {            // 设置配置项            properties.setProperty("username", "admin");            properties.setProperty("password", "123456");            // 保存配置文件            FileOutputStream fileOutputStream = new FileOutputStream("config.properties");            properties.store(fileOutputStream, null);            fileOutputStream.close();            System.out.println("Config file saved successfully.");        } catch (IOException e) {            e.printStackTrace();        }    }}

上述示例中,假设配置文件名为config.properties,内容如下:

username=adminpassword=123456

读取配置文件时,使用Properties类的load方法加载文件流,并使用getProperty方法获取配置项的值。

写入配置文件时,使用Properties类的setProperty方法设置配置项的值,并使用store方法保存到文件中。

请注意,读写配置文件时,需要处理IOException异常。另外,配置文件的路径可以根据实际情况进行调整。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言