Java Properties 属性文件读取写入工具类
自己编写的一个简单工具类,方便操作属性文件
构造方法必须传入属性文件的位置,工具类会自动定位到项目的物理根目录到/Webroot后面需要传入路径,传入的路径记住以/开头。
##现在工具类未对太多的安全性验证。
Java代码- 1.package cn.net.withub.smsp.common.utils;
- 2.
- 3.import java.io.File;
- 4.import java.io.FileInputStream;
- 5.import java.io.FileOutputStream;
- 6.import java.io.InputStream;
- 7.import java.util.Properties;
- 8.
- 9.import org.apache.commons.logging.Log;
- 10.import org.apache.commons.logging.LogFactory;
- 11.
- 12.import bsh.This;
- 13.
- 14.import cn.net.withub.lab.SMGPLab;
- 15.
- 16./**
- 17. * 配置文件读取和写入工具类
- 18. * @author Jacky.Jiang
- 19. *
- 20. */
- 21.public class PropertiesHelper {
- 22. private static Log logger = LogFactory.getLog(This.class);
- 23.
- 24. private String project_root = "";
- 25. private File file = null;
- 26.
- 27.
- 28. public PropertiesHelper(String filePath) {
- 29. //构造时获取到项目的物理根目录
- 30. project_root = this.getClass().getResource("/").toString().replace("file:/", "");
- 31. project_root = project_root.substring(0,project_root.indexOf("/WEB-INF"));
- 32.
- 33. if(filePath != null && filePath.length() > 0){
- 34. try {
- 35. file = new File(project_root+filePath);
- 36.
- 37. } catch (Exception e) {
- 38. logger.error(e);
- 39. }
- 40. }
- 41. }
- 42.
- 43. public String getProperties(String key){
- 44. InputStream fis = null;
- 45. try {
- 46. Properties prop = new Properties();
- 47. fis = new FileInputStream(getAbsolutePath());
- 48.
- 49. prop.load(fis);
- 50.
- 51. return prop.getProperty(key);
- 52.
- 53. } catch (Exception e) {
- 54. logger.error(e);
- 55. }finally{
- 56. try{if(fis != null){fis.close();}}catch(Exception e){}
- 57. }
- 58.
- 59. return "";
- 60. }
- 61.
- 62. public void setProperties(String key,String value)throws Exception{
- 63. Properties prop = new Properties();
- 64.
- 65.
- 66. FileOutputStream outputFile = null;
- 67. InputStream fis = null;
- 68. try {
- 69. //输入流和输出流要分开处理, 放一起会造成写入时覆盖以前的属性
- 70. fis = new FileInputStream(getAbsolutePath());
- 71. //先载入已经有的属性文件
- 72. prop.load(fis);
- 73.
- 74. //追加新的属性
- 75. prop.setProperty(key, value);
- 76.
- 77. //写入属性
- 78. outputFile = new FileOutputStream(getAbsolutePath());
- 79. prop.store(outputFile, "");
- 80.
- 81. outputFile.flush();
- 82. } catch (Exception e) {
- 83. logger.error(e);
- 84. throw e;
- 85. }finally{
- 86. try{if(fis != null){fis.close();}}catch(Exception e){}
- 87. try{if(outputFile != null){outputFile.close();}}catch(Exception e){}
- 88. }
- 89. }
- 90.
- 91.
- 92. public String getAbsolutePath(){
- 93. try {
- 94. return file.getAbsolutePath();
- 95. } catch (Exception e) {
- 96. logger.error(e);
- 97. }
- 98. return "";
- 99. }
- 100.}
复制代码 |