CivilCodeFileConf.java 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package com.genersoft.iot.vmp.conf;
  2. import com.genersoft.iot.vmp.common.CivilCodePo;
  3. import com.genersoft.iot.vmp.utils.CivilCodeUtil;
  4. import lombok.extern.slf4j.Slf4j;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.boot.CommandLineRunner;
  7. import org.springframework.context.annotation.Configuration;
  8. import org.springframework.context.annotation.Lazy;
  9. import org.springframework.core.annotation.Order;
  10. import org.springframework.core.io.ClassPathResource;
  11. import org.springframework.util.ObjectUtils;
  12. import java.io.BufferedReader;
  13. import java.io.File;
  14. import java.io.InputStream;
  15. import java.io.InputStreamReader;
  16. import java.nio.charset.StandardCharsets;
  17. import java.nio.file.Files;
  18. /**
  19. * 启动时读取行政区划表
  20. */
  21. @Slf4j
  22. @Configuration
  23. @Order(value=14)
  24. public class CivilCodeFileConf implements CommandLineRunner {
  25. @Autowired
  26. @Lazy
  27. private UserSetting userSetting;
  28. @Override
  29. public void run(String... args) throws Exception {
  30. if (ObjectUtils.isEmpty(userSetting.getCivilCodeFile())) {
  31. log.warn("[行政区划] 文件未设置,可能造成目录刷新结果不完整");
  32. return;
  33. }
  34. InputStream inputStream;
  35. if (userSetting.getCivilCodeFile().startsWith("classpath:")){
  36. String filePath = userSetting.getCivilCodeFile().substring("classpath:".length());
  37. ClassPathResource civilCodeFile = new ClassPathResource(filePath);
  38. if (!civilCodeFile.exists()) {
  39. log.warn("[行政区划] 文件<{}>不存在,可能造成目录刷新结果不完整", userSetting.getCivilCodeFile());
  40. return;
  41. }
  42. inputStream = civilCodeFile.getInputStream();
  43. }else {
  44. File civilCodeFile = new File(userSetting.getCivilCodeFile());
  45. if (!civilCodeFile.exists()) {
  46. log.warn("[行政区划] 文件<{}>不存在,可能造成目录刷新结果不完整", userSetting.getCivilCodeFile());
  47. return;
  48. }
  49. inputStream = Files.newInputStream(civilCodeFile.toPath());
  50. }
  51. BufferedReader inputStreamReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
  52. int index = -1;
  53. String line;
  54. while ((line = inputStreamReader.readLine()) != null) {
  55. index ++;
  56. if (index == 0) {
  57. continue;
  58. }
  59. String[] infoArray = line.split(",");
  60. CivilCodePo civilCodePo = CivilCodePo.getInstance(infoArray);
  61. CivilCodeUtil.INSTANCE.add(civilCodePo);
  62. }
  63. inputStreamReader.close();
  64. inputStream.close();
  65. if (CivilCodeUtil.INSTANCE.isEmpty()) {
  66. log.warn("[行政区划] 文件内容为空,可能造成目录刷新结果不完整");
  67. }else {
  68. log.info("[行政区划] 加载成功,共加载数据{}条", CivilCodeUtil.INSTANCE.size());
  69. }
  70. }
  71. }