Properties文件解析

àì夳堔傛蜴生んèń 2022-03-27 04:43 435阅读 0赞
  1. package com.winskysoft.bbk.tools;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.FileNotFoundException;
  5. import java.io.FileOutputStream;
  6. import java.io.IOException;
  7. import java.io.InputStream;
  8. import java.util.Properties;
  9. import javax.servlet.ServletContext;
  10. import javax.servlet.http.HttpServlet;
  11. /**
  12. * 读取配置文件
  13. *
  14. */
  15. public class PropertiesUtil {
  16. private String filename;
  17. private Properties p;
  18. private FileInputStream in;
  19. private FileOutputStream out;
  20. public PropertiesUtil(String filename) {
  21. this.filename = filename;
  22. File file = new File(filename);
  23. try {
  24. in = new FileInputStream(file);
  25. p = new Properties();
  26. p.load(in);
  27. in.close();
  28. } catch (FileNotFoundException e) {
  29. System.err.println("配置文件config.properties找不到!");
  30. e.printStackTrace();
  31. } catch (IOException e) {
  32. System.err.println("读取配置文件config.properties错误!");
  33. e.printStackTrace();
  34. }
  35. }
  36. public PropertiesUtil(InputStream in){
  37. try {
  38. p = new Properties();
  39. p.load(in);
  40. } catch (IOException e) {
  41. System.err.println("读取配置文件config.properties错误!");
  42. e.printStackTrace();
  43. }
  44. }
  45. public static String getConfigFile(HttpServlet hs) {
  46. return getConfigFile(hs, "config.properties");
  47. }
  48. private static String getConfigFile(HttpServlet hs, String configFileName) {
  49. String configFile = "";
  50. ServletContext sc = hs.getServletContext();
  51. configFile = sc.getRealPath("/" + configFileName);
  52. if (configFile == null || configFile.equals("")) {
  53. configFile = "/" + configFileName;
  54. }
  55. return configFile;
  56. }
  57. public void list() {
  58. p.list(System.out);
  59. }
  60. public String getValue(String itemName) {
  61. return p.getProperty(itemName);
  62. }
  63. public String getValue(String itemName, String defaultValue) {
  64. return p.getProperty(itemName, defaultValue);
  65. }
  66. public void setValue(String itemName, String value) {
  67. p.setProperty(itemName, value);
  68. }
  69. public void saveFile(String filename, String description) throws Exception {
  70. try {
  71. File f = new File(filename);
  72. out = new FileOutputStream(f);
  73. p.store(out, description);
  74. out.close();
  75. } catch (IOException ex) {
  76. throw new Exception("无法保存指定的配置文件:" + filename);
  77. }
  78. }
  79. public void saveFile(String filename) throws Exception {
  80. saveFile(filename, "");
  81. }
  82. public void saveFile() throws Exception {
  83. if (filename.length() == 0)
  84. throw new Exception("需指定保存的配置文件名");
  85. saveFile(filename);
  86. }
  87. public void deleteValue(String value) {
  88. p.remove(value);
  89. }
  90. }

发表评论

表情:
评论列表 (有 0 条评论,435人围观)

还没有评论,来说两句吧...

相关阅读