properties文件的读写使用例子

来源:互联网 发布:controlcenter软件下载 编辑:程序博客网 时间:2024/06/05 17:34

 

package com.zyj;

import java.io.BufferedInputStream;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.util.Enumeration;

import java.util.Properties;

import java.util.concurrent.BlockingQueue;

public class PropertiesIO {

//根据key读取value

    public static String readValue(String filePath, String key){

        Properties props = new Properties();

        String value=null;

        try{

        props.load(PropertiesIO.class.getClassLoader().getResourceAsStream(filePath));//此方法只读

            value = props.getProperty(key);

          //   in.close();

        }catch(Exception e){

            e.printStackTrace();

        }

        return value;

    }

 

    //读取properties的全部信息

    public static void readProperties(String filePath){

        Properties props = new Properties();

        try{

            InputStream in = new BufferedInputStream(PropertiesIO.class.getClassLoader().getResourceAsStream(filePath));

            props.load(in);

            Enumeration<?> en = props.propertyNames();

            while(en.hasMoreElements()){

                String key = (String)en.nextElement();

                String property = props.getProperty(key);

                System.out.println(key + " : " + property);

            }

            in.close();

        }catch(Exception e){

            e.printStackTrace();

        }finally{

        }

    }

 

    //写入properties信息

    public static void writeProperties(String filePath, String parameterName, String parameterValue){

        Properties props = new Properties();

        try{

        InputStream fis = new FileInputStream(filePath);

//            InputStream fis = new BufferedInputStream(PropertiesIO.class.getClassLoader().getResourceAsStream(filePath));

            //从输入流中读取属性列表(键和元素对)

            props.load(fis);

             fis.close();

            //调用Hashtable的方法put。使用getProperty方法提供并行性

            //强制要求为属性的键和值使用字符串。返回值是Hashtable调用put的结果

            OutputStream fos = new FileOutputStream(filePath);

            props.setProperty(parameterName, parameterValue);

            //以适合使用load方法加载到Properties表中的格式,将此Properties表中的属性列表(键和元素对)写入输出流

            //props.store(fos, "Update '" + parameterName + "' value");

            props.store(fos,"");

          fos.close();//------------------------------------important

        }catch(IOException e){

            e.printStackTrace();

        }

    }

 

    public static void main(String[] args) {

  PropertiesIO.writeProperties("D:/abcdefghijklmnopqrstuvwxyz/source/ja08/PropertiesTest/src/ziyuan.properties","a","xxx");

//      System.out.println(PropertiesIO.readValue("ziyuan.properties","a"));

//        PropertiesIO.readProperties("ziyuan.properties");

    }

}



 
  • 大小: 26.9 KB
  • 查看图片附件
原创粉丝点击