PropertiesUtils.java 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package com.huimv.video.util;
  2. import java.io.*;
  3. import java.util.Iterator;
  4. import java.util.Map;
  5. /**
  6. * @Project : huimv.shiwan
  7. * @Package : com.huimv.video.util
  8. * @Description : TODO
  9. * @Author : yuxuexuan
  10. * @Create : 2021/3/4 0008 16:03
  11. **/
  12. public class PropertiesUtils {
  13. /**
  14. * 根据key获取prpperties中的某一项值
  15. * @param key
  16. * @param fileURL properties地址
  17. * @return
  18. */
  19. public static String getFileIO(String key, String fileURL) {
  20. java.util.Properties prop = new java.util.Properties();
  21. InputStream in=null;
  22. try {
  23. in = new BufferedInputStream(new FileInputStream(fileURL));
  24. prop.load(in);
  25. //根据key 获得所对应的value
  26. return prop.getProperty(key);
  27. } catch (Exception e) {
  28. e.printStackTrace();
  29. } finally {
  30. try {
  31. in.close();
  32. } catch (IOException e) {
  33. e.printStackTrace();
  34. }
  35. }
  36. return null;
  37. }
  38. /**
  39. * 修改并写properties
  40. * @param map
  41. * @param fileURL
  42. * @return
  43. */
  44. public static boolean writeData(Map<String, Object> map, String fileURL) {
  45. java.util.Properties prop = new java.util.Properties();
  46. InputStream fis = null;
  47. OutputStream fos = null;
  48. try {
  49. //获得文件
  50. File file = new File(fileURL);
  51. //查看文件是否存在
  52. if (!file.exists()){
  53. return false;
  54. }
  55. fis = new FileInputStream(file);
  56. prop.load(fis);
  57. fis.close();// 一定要在修改值之前关闭fis
  58. fos = new FileOutputStream(file);
  59. Iterator<Map.Entry<String, Object>> valueSet = map.entrySet().iterator();
  60. //便利map的值
  61. while (valueSet.hasNext()) {
  62. Map.Entry<String, Object> entry = (Map.Entry<String, Object>) valueSet.next();
  63. String key = entry.getKey().toString();
  64. String value= entry.getValue().toString();
  65. prop.setProperty(key, value);
  66. prop.store(fos, "Update '" + key + "' value");
  67. }
  68. fos.close();
  69. return true;
  70. } catch (IOException e) {
  71. e.printStackTrace();
  72. } finally {
  73. try {
  74. fos.close();
  75. fis.close();
  76. } catch (IOException e) {
  77. e.printStackTrace();
  78. }
  79. }
  80. return false;
  81. }
  82. }