欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java读取配置文件信息

程序员文章站 2022-04-25 14:29:19
...
1、先引包
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Properties;


2、根据key取值
public static void main(String[] args) {
        String str = getValues("f:/file.properties","filePath1");
        System.out.println(str);
    }

    public static String getValues(String fileName , String key){
        String values = "";
        try{
            if(null != fileName && !fileName.trim().equals("")){
                Properties prop = new Properties();
                InputStream in = new BufferedInputStream (new FileInputStream(fileName));
                prop.load(in);     ///加载属性列表
                values = prop.getProperty(key);
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return values;
    }


3、扫描配置文件中所有信息
public static void main(String[] args) {
        Properties prop = new Properties();
        try{
            //读取属性文件
            InputStream in = new BufferedInputStream (new FileInputStream("f:/file.properties"));
            prop.load(in);     ///加载属性列表
            prop.getProperty()
            Iterator<String> it=prop.stringPropertyNames().iterator();
            while(it.hasNext()){
                String key=it.next();
                System.out.println(key);//打印key
                System.out.println(prop.getProperty(key));//打印值
            }
            in.close();

            ///保存属性到b.properties文件
            FileOutputStream oFile = new FileOutputStream("b.properties", true);//true表示追加打开
            prop.setProperty("phone", "10086");
            prop.store(oFile, "The New properties file");
            oFile.close();
        }
        catch(Exception e){
            System.out.println(e);
        }
    }