Java Properties文件操作

 

Properties(java.util.Properties),常用来读写Java配置文件

此类常用的方法有:

  load(InputStream in),加载待读取的属性文件的字节流

    getProperty(String key),通过键值获取属性值

  put(String key,String value),增加待写入配置文件的键值对

  setProperty(String key,String value),修改配置文件中的属性值

  store(OutputStream out,String comment),将设置好的键值对写入配置文件中 

 

代码示例:

package com.seven.javaSE;

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 interface PropertiesDemo {
    public static void main(String[] args) {
        readConfig();
        writeConfig();
    }
    
    //读取xxx.properties配置文件
    public static void readConfig() {
        Properties p = new Properties();
        try {
            InputStream in = new FileInputStream("src/com/seven/javaSE/info_zh_CN.properties");
            p.load(in);
            String username = p.getProperty("username");
            in.close();
            System.out.println(username);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    //修改配置文件
    public static void writeConfig() {
        Properties p = new Properties();
        p.put("username", "藤原豆腐渣渣");
        p.setProperty("username", "seven");
        try {
            OutputStream out = new FileOutputStream("src/com/seven/javaSE/info_zh_CN.properties");
            p.store(out, "wirte config");
            
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 

posted @ 2022-06-22 21:52  藤原豆腐渣渣  阅读(135)  评论(0编辑  收藏  举报