java读写properties文件

本文介绍了一个Java程序如何读取和写入属性文件的具体实现。包括获取文件路径、使用Properties类加载文件并读取指定参数值,以及更新属性文件中的值。

import java.io.File;

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.net.URL;

import java.util.Properties;

 

 

 

public class Test {

      //path需要文件的绝对路径

public static String readProperties(String fileName, String parameterName) { 

        String filePath=Test.class.getResource("/")+"";

      //替换所获得路径的/bin为/src

       //conf/表示配置文件所在的包名,根据不同的包进行修改

String fPath=filePath.replaceAll("/bin","/src")+"conf/"+fileName;

        //去掉path前面的file:/

String path = fPath.replaceAll("file:/","");

        System.out.println(path);

File file = new File(path);

   String value = ""; 

   Properties prop = new Properties(); 

   try { 

       InputStream fis = new FileInputStream(file); 

       prop.load(fis); 

       value = prop.getProperty(parameterName); 

   } catch (Exception e) { 

       e.printStackTrace(); 

   } 

   return value; 

public static Properties readProperties2(String fileName, String parameterName) { 

String filePath=Test.class.getResource("/")+"";

String fPath=filePath.replaceAll("/bin","/src")+"conf/"+fileName;

String path = fPath.replaceAll("file:/","");

       System.out.println(path);

File file = new File(path);

  

   Properties prop = new Properties(); 

   try { 

       InputStream fis = new FileInputStream(file); 

       prop.load(fis); 

      // value = prop.getProperty(parameterName); 

   } catch (Exception e) { 

       e.printStackTrace(); 

   } 

   return prop; 

public static void writeProperties(Properties prop,String fileName){

String filePath=Test.class.getResource("/")+"";

String fPath=filePath.replaceAll("/bin","/src")+"conf/"+fileName;

String path = fPath.replaceAll("file:/","");

       System.out.println(path);

File file = new File(path);

   try {   

      

       OutputStream fos = new FileOutputStream(file);   

       // 调用 Hashtable 的方法 put。   

       prop.setProperty("jdbc.url", "新的字符串");   

       // 以适合使用 load 方法加载到 Properties 表中的格式,   

       // 将此 Properties 表中的属性列表(键和元素对)写入输出流   

       prop.store(fos, "Update '" + "x" + "' value");   

   } catch (FileNotFoundException e) {   

       e.printStackTrace();   

   } catch (IOException e) {   

       e.printStackTrace();   

   }   

}

 

public static void main(String args[]){

String fileName="1.properties";

Properties properties = readProperties2(fileName,"jdbc.url");

writeProperties(properties,fileName);

System.out.println(readProperties(fileName,"jdbc.url"));

}

}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值