springboot reads the file after typing into jar package can not access the solution

  • 2021-10-16 01:40:58
  • OfStack

springboot reads the file and cannot be accessed after it is typed into jar package

There is a situation in the latest development. After springboot is typed into jar package, the file cannot be read. The reason is that after packaging, the virtual path of the file is invalid and can only be read through stream.

File under resources


public void test() {
  List<String> names = new ArrayList<>();
  InputStreamReader read = null;
  try {
   ClassPathResource resource = new ClassPathResource("name.txt");
 
   InputStream inputStream = resource.getInputStream();
   read = new InputStreamReader(inputStream, "utf-8");
   BufferedReader bufferedReader = new BufferedReader(read);
   String txt = null;
   while ((txt = bufferedReader.readLine()) != null) {
    if (StringUtils.isNotBlank(txt)) {
     names.add(txt);
    }
   }
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   if (read != null) {
    try {
     read.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
 }

springboot can't access static folder in the background when playing jar package

1.ResourceUtils

Usually we write spring boot project occasionally in the background to use the files under classpath, 1 we all write like this


File file = ResourceUtils.getFile("classpath:static/image/image");

Under such circumstances, there was no problem. However, this file will not be found after running with jar package.

The file under Resource exists in the file jar, and there is no real path on the disk. It is actually a path inside jar. Therefore, the file cannot be obtained correctly by ResourceUtils. getFile or this. getClass (). getResource ("") method.

In this case. Sometimes project documents are placed outside the project, but it is easy to delete these things by mistake.

2.ClassPathResource


 ClassPathResource cpr = new ClassPathResource("static/image/image/kpg");
 InputStream in = cpr.getInputStream();

3. ResourceLoader


 public class ResourceRenderer {
 public static InputStream resourceLoader(String fileFullPath) throws IOException {
        ResourceLoader resourceLoader = new DefaultResourceLoader();
        return resourceLoader.getResource(fileFullPath).getInputStream();
    }
}

Usage


InputStream in = ResourceRenderer.resourceLoader("classpath:static/image/image");

This perfectly solves the problem that the path under jar packet cannot be accessed.


Related articles: