Regarding the problem of obtaining file resources under resources after java is packaged into jar

Recently, when writing code, I found that when the resources under the resources file are obtained through the following two methods, they can be obtained by running in the editor, but they cannot be obtained after being packaged into a jar package. Later, I found out that after the original project was packaged into a jar package It is a file, not a folder, so the resources under the resources file cannot be obtained in this way.

//1.通过ClassPathResource 类获取
ClassPathResource resource = new ClassPathResource("pdfTemplates/logo.jpg");
//2.通过ResourceUtils获取
ResourceUtils.getFile("classpath:").getPath();

So what to do, we can obtain the resources under the packaged resources in the following way.

		//读取resources的文件,打成jar包后不能直接读取,需要通过这种方式读取
		//这个是直接取的resources下的文件,所以直接写resources下的相对路径就行,不用加classpath:
        InputStream is = this.getClass().getClassLoader().getResourceAsStream("pdfTemplates/logo.jpg");

I have acquired an image resource. This acquisition method obtains a file stream, which can be converted into the way you want to use directly. I converted it into byte[].
Hope to help everyone! ! !

Guess you like

Origin blog.csdn.net/qq_45699784/article/details/129295569