[Springboot] SpringBoot cannot read static files after printing the Jar package, showing that the file does not exist

Uncle Cthulhu 2022-11-24 21:25:03 阅读数:654


1. First of all, it is wrong, as shown in the figure below, but after I open it with compressed files, the file exists, as shown in the figure below:

2. Solutions

1.1 First save the file in a folder in Resources, as shown in the figure:

1.2 Then use this method to read the file content:

JSONObject jsonObject;String input;log.info("File address: {}", fileName);try {// SpringBoot can only read files in this wayClassPathResource cpr = new ClassPathResource(fileName);byte[] bdata = FileCopyUtils.copyToByteArray(cpr.getInputStream());input = new String(bdata, StandardCharsets.UTF_8);//input = FileUtils. readFileToString(new File(path), "UTF-8");jsonObject = JSONObject. parseObject(input);return jsonObject;} catch (IOException e) {log.error("json parsing failed", e);throw new ProcureException. ProcureJsonErrorException();}

3. Finally, the log is successfully printed and the parameters are read

copyright:author[Uncle Cthulhu],Please bring the original link to reprint, thank you. https://en.javamana.com/2022/328/202211242120377798.html