package cn.cslg.pas.common.utils; import org.springframework.boot.system.ApplicationHome; import org.springframework.stereotype.Service; import java.io.*; import java.nio.charset.StandardCharsets; @Service public class FileUtils { public static final String FILE_SEPARATOR = System.getProperty("file.separator"); public static final String COMMON_FILE = "file"; public static final String BACKUP_FILE = "backup"; public static String getStaticPath(String fileName) { //ApplicationHome类 返回target目录层级 ApplicationHome ah = new ApplicationHome(FileUtils.class); //获取 applicationHome 内的路径 ...\target\classes 到这一层级下 File file = ah.getSource(); //获取 file的parentFile 即最后一级之前的所有层级路径(包括盘符) 这里能获得到的最终层级为 ...\target 后续用FILE_SEPARATOR(系统路径分割通配符 即 "\") 以及fileName拼接生成存放文件的目录层级 即为根目录 root String rootPath = file.getParentFile().toString() + FILE_SEPARATOR + fileName; //根据上方生成的根目录路径 生成对应文件夹 没有就新建 File root = new File(rootPath); if (!root.exists()) { root.mkdir(); } //返回的最终形式为 盘符:\项目层级\target\file return rootPath; } public String analysisJsonFile() { ApplicationHome ah = new ApplicationHome(BackupUtils.class); File file = ah.getSource(); String settingFilePath = file.getParentFile().toString() + FileUtils.FILE_SEPARATOR + "uploadSetting.json"; BufferedReader reader = null; StringBuilder last = new StringBuilder(); InputStreamReader inputStreamReader; try (FileInputStream fileInputStream = new FileInputStream(settingFilePath)) { inputStreamReader = new InputStreamReader(fileInputStream, StandardCharsets.UTF_8); reader = new BufferedReader(inputStreamReader); String tempString; while ((tempString = reader.readLine()) != null) { last.append(tempString); } reader.close(); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } return last.toString(); } }