您的位置:首页 > 运维架构

在web中如何更改properties文件的内容,绝对经典!

2015-12-21 16:58 351 查看
public class PropUtil { 

/** * 根据KEY,读取文件对应的值 *

@param filePath 文件路径,即文件所在包的路径,例如:java/util/config.properties * 

@param key 键 * 

@return key对应的值 */ 

public static String getProp(String filename, String key) { 

try { 

Properties props = new Properties(); 

String filepath = PropUtil.class.getClassLoader().getResource("/").getPath() + filename; 

File file = new File(filepath); 

InputStream in = new FileInputStream(file); 

props.load(in);

 in.close(); 

String value = props.getProperty(key); 

return value; 

} catch (Exception e)

 { e.printStackTrace(); return null; } }

 /** * 修改或添加键值对 如果key存在,修改, 反之,添加。 

* @param filePath 文件路径,即文件所在包的路径,例如:java/util/config.properties 

* @param key 键 * @param value 键对应的值 

*/ 

public static void setProp(String filename, String key, String value) { 

try { 

Properties prop = new Properties();

String filepath = PropUtil.class.getClassLoader().getResource("/").getPath() + filename; 

File file = new File(filepath);

InputStream in = new FileInputStream(file);

prop.load(in); //一定要在修改值之前关闭fis 

in.close(); 

System.out.println("filepath---------->" + filepath);

 OutputStream fos = new FileOutputStream(file); prop.setProperty(key, value); //保存,并加入注释 

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

fos.flush(); 

fos.close(); 

} catch (Exception e) {

 e.printStackTrace(); 

} } }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java web 更改properties