`

java操作properties属性文件

    博客分类:
  • java
 
阅读更多

 

 

 java更新或增加属性

/**
    * 写入properties信息
    * @param filePath  绝对路径(包括文件名和后缀名)
    * @param parameterName  名称
    * @param parameterValue 值
    */
   public static void writeProperties(String filePath,String parameterName,String parameterValue) {
	Properties props = new Properties();
	try {
	
               	//如果文件不存在,创建一个新的
		        File file=new File(filePath);
		        if(!file.exists()){
			   ToolKit.writeLog(Setting.class.getName(), "sharedata.properties 文件不存在,创建一个新的!");
			file.createNewFile();
		}

                       InputStream fis = new FileInputStream(filePath);
		// 从输入流中读取属性列表(键和元素对)
		props.load(fis);
		fis.close();
		OutputStream fos = new FileOutputStream(filePath);
		props.setProperty(parameterName, parameterValue);
		// 以适合使用 load 方法加载到 Properties 表中的格式,
		// 将此 Properties 表中的属性列表(键和元素对)写入输出流
		props.store(fos, parameterName);
		fos.close(); // 关闭流
	} catch (IOException e) {
        System.err.println("Visit "+filePath+" for updating "+parameterName+" value error");
        writeLog(This.class.getName(), "Visit "+filePath+" for updating "+parameterName+" value error", e);
       }
   }

 

java读取属性(相对路径)

  /**
    *filename: 相对路径+文件名(不要后缀) 
    */
public synchronized static String getPropertyFromFile(String filename, String key)
    {
        ResourceBundle rb = ResourceBundle.getBundle(filename);
        return rb.getString(key).trim();
    }

 

 

 java读取属性(绝对路径)

/**
	   *
	   * @Title: readValue 
	   * @Description: TODO  通过绝对路径获取properties文件属性,  根据key读取value
	   * @param filePath  properties文件绝对路径(包括文件名和后缀)
	   * @param key   属性key
	   * @return String 返回value
	   */
    public static String readValue(String filePath, String key){
        Properties props = new Properties();
        InputStream in=null;
        try{
            in = new BufferedInputStream(new FileInputStream(filePath));
            props.load(in);
            String value = props.getProperty(key);
            return value;
             
        }catch(Exception e){
            e.printStackTrace();
            return null;
        }finally{
        	try {
				in.close();//-----------------------------------important
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
    }

 

main函数示例

/** 
	 * 本类主要是对config。properties的密码进行修改
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
          
                //写文件
		String passwork = “123”;
                  //更改src的config包下的config.properties文件中的“userPassword”属性的值
		writeProperties("config/config.properties","userPassword",passwork); //config.properties一定要写完整
		 

		 //从文件中取出userPassword,
		 String decStr=getPropertyFromFile("config/config", "userPassword");
		System.out.println("============"+ decStr);
	}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics