0
点赞
收藏
分享

微信扫一扫

编辑文章 - 博客频道 - CSDN.NET

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(); 
} } }

举报

相关推荐

0 条评论