Verifying getInputStream Works for Files Inside a Spring Boot Jar

I previously wrote "The Big Pitfall of Reading Files After Packaging a Spring Boot Project Into a Jar: ClassPathResource Fails to Read Files on the Classpath" and published it on my blog and CSDN. I hadn't logged into CSDN in a long while; today I did, and found two commenters both saying they tried my approach and couldn't get anything.

I previously wrote The Big Pitfall of Reading Files After Packaging a Spring Boot Project Into a Jar: ClassPathResource Fails to Read Files on the Classpath and published it on my blog and CSDN.

I hadn’t logged into CSDN in a long while; today I did, and found two commenters both saying they tried my approach and couldn’t get anything.

So let me run it myself again — write a demo and verify with my own hands whether getInputStream can actually read a file inside a Jar.

Key code below; the whole project lives at https://github.com/renfei/demo/tree/master/spring/jar-read-file

@RequestMapping("/")
public void getImageTest(HttpServletResponse response) throws IOException {
    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    Resource[] resources = resolver.getResources("image/WX20210312-225547.png");
    Resource resource = resources[0];
    try (InputStream input = resource.getInputStream()) {
        response.setContentType("image/png");
        int len = 0;
        byte[] buffer = new byte[1024];
        while ((len = input.read(buffer)) != -1) {
            System.out.println("reading stream, writing to response output stream");
            response.getOutputStream().write(buffer, 0, len);
        }
    }
}

I’m also on all the big video platforms now, and to prove this method works I screen-recorded the whole process:

Too lazy to paste links for WeChat Channels, Douyin and Xigua Video.