FileUtils.java 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package cn.cslg.pas.common.utils;
  2. import org.springframework.boot.system.ApplicationHome;
  3. import org.springframework.stereotype.Service;
  4. import java.io.*;
  5. import java.nio.charset.StandardCharsets;
  6. @Service
  7. public class FileUtils {
  8. public static final String FILE_SEPARATOR = System.getProperty("file.separator");
  9. public static final String COMMON_FILE = "file";
  10. public static final String BACKUP_FILE = "backup";
  11. public static String getStaticPath(String fileName) {
  12. //ApplicationHome类 返回target目录层级
  13. ApplicationHome ah = new ApplicationHome(FileUtils.class);
  14. //获取 applicationHome 内的路径 ...\target\classes 到这一层级下
  15. File file = ah.getSource();
  16. //获取 file的parentFile 即最后一级之前的所有层级路径(包括盘符) 这里能获得到的最终层级为 ...\target 后续用FILE_SEPARATOR(系统路径分割通配符 即 "\") 以及fileName拼接生成存放文件的目录层级 即为根目录 root
  17. String rootPath = file.getParentFile().toString() + FILE_SEPARATOR + fileName;
  18. //根据上方生成的根目录路径 生成对应文件夹 没有就新建
  19. File root = new File(rootPath);
  20. if (!root.exists()) {
  21. root.mkdir();
  22. }
  23. //返回的最终形式为 盘符:\项目层级\target\file
  24. return rootPath;
  25. }
  26. public String analysisJsonFile() {
  27. ApplicationHome ah = new ApplicationHome(BackupUtils.class);
  28. File file = ah.getSource();
  29. String settingFilePath = file.getParentFile().toString() + FileUtils.FILE_SEPARATOR + "uploadSetting.json";
  30. BufferedReader reader = null;
  31. StringBuilder last = new StringBuilder();
  32. InputStreamReader inputStreamReader;
  33. try (FileInputStream fileInputStream = new FileInputStream(settingFilePath)) {
  34. inputStreamReader = new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
  35. reader = new BufferedReader(inputStreamReader);
  36. String tempString;
  37. while ((tempString = reader.readLine()) != null) {
  38. last.append(tempString);
  39. }
  40. reader.close();
  41. } catch (IOException e) {
  42. e.printStackTrace();
  43. } finally {
  44. if (reader != null) {
  45. try {
  46. reader.close();
  47. } catch (IOException e) {
  48. e.printStackTrace();
  49. }
  50. }
  51. }
  52. return last.toString();
  53. }
  54. }