IO_File类使用:Properties工具类使用

Properties工具类文件操作
Properties(Java.util.Properties),主要用于读取Java的配置文件,各种语言都有自己所支持的配置文件,配置文件中很多变量时经常改变的,这样做也是为了方便用户让用户能够脱离程序本身修改相关的变量设置。

ResourceBundle类,只读
Properties类,可读可写

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 PropertiesDemo {
    
    //静态的属性,才能被静态的方法调用
    private static String version=null;
    private static String username=null;
    private static String password=null;
    
    //静态代码块:只会执行一次;加载改类的时候就会读取该方法,从而只读取一次,避免每次都读取配置文件
    static {
        readConfig();
    }

    
    public static void main(String[] args) {
        writeConfig("3","smsweb","987654");
        //readConfig();
        System.out.println(PropertiesDemo.version);
        System.out.println(PropertiesDemo.username);
        System.out.println(PropertiesDemo.password);
    }
    
    
    //读配置文件
    public static void readConfig() {
        Properties p = new Properties();
        try {
            //通过当期线程的类加载器对象,来加载指定包下的配置文件
            InputStream inStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("com/res/config.properties");
            
            //InputStream inStream = new FileInputStream("config.properties");  当配置文件不和该程序文件再同一工程目录下时不能这么定义输入流
            
            //将配置文件信息加载到Properties对象中保存
            p.load(inStream);
            //从Properties对象中读取配置信息
            version = p.getProperty("app.version");
            username = p.getProperty("db.username");
            password = p.getProperty("db.password");
            inStream.close();
            
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    
    //写配置文件:1、先put写入到Properties对象里,2、再从Properties对象里写出来
    public static void writeConfig(String version,String username,String password) {
        Properties pw = new Properties();
        pw.put("app.version", version);
        pw.put("db.username", username);
        pw.put("db.password", password);
        try {
            OutputStream out =new FileOutputStream("config.properties");
            pw.store(out, "update config");
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    
}

你可能感兴趣的:(IO_File类使用:Properties工具类使用)