Home >Java >javaTutorial >How to solve the problem that springboot cannot access the file after reading it into a jar package
In the latest development, there is a situation where springboot cannot read the file after packaging it into a jar package. The reason is that after packaging, the virtual path of the file is invalid and can only be read through the stream.
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(); } } } }
Usually when we write spring boot projects Occasionally, files under the classpath are used in the background. Generally, we write them like this
File file = ResourceUtils.getFile("classpath:static/image/image");
In this case, there is no problem. But after running the jar package, the file will not be found.
The file under Resource exists in the jar file. There is no real path on the disk. It is actually a path inside the jar. Therefore, the file cannot be obtained correctly through the 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.
ClassPathResource cpr = new ClassPathResource("static/image/image/kpg"); InputStream in = cpr.getInputStream();
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 of inaccessible paths under the jar package.
The above is the detailed content of How to solve the problem that springboot cannot access the file after reading it into a jar package. For more information, please follow other related articles on the PHP Chinese website!