Talk about web project read classpath path below the file

  • 2020-12-20 03:35:13
  • OfStack

This paper mainly studies the problem of reading files in classpath path under web project, as follows.

The first two categories are web containers

The first is the common web project, like Tomcat container. The feature is that the compressed package will be uncompressed into a folder with the start of the container. When the project accesses, it is actually to access the folder, not jar or war package.

This is whatever you do by getting the path this.getClass().getResource("/")+fileName

Method to get a stream this.getClass().getResourceAsStream(failName);


import org.springframework.util.ResourceUtils;
File file= ResourceUtils.getFile("classpath:test.txt");

or


ClassPathResource classPathResource = new ClassPathResource("test.txt");

Access to files: classPathResource .getFile();

Get file flow: classPathResource .getInputStream();

The second is the embedded web container, which is characterized by having only one jar file, which is not unzipped after the container is started, and the jar package or war package is actually accessed by the project

This is the most common pit, the biggest pit is, read it the first way, debug it on eclipse, run it perfectly, run it on linux, it doesn't work.

The first method is to get the path this.getClass().getResource("/")+fileName , the method to get the flow this.getClass().getResourceAsStream(failName);

In the local runtime, the cliff can find, you print out the path, yes, it's our eclipse working directory, project directory, but under target.

Now give you analyze why go to online, GG, is very simple, online embedded project, we will only put 1 jar file, I understand is jar path is couldn't get inside, something jar is closed, unlike folder, always can't c: / home/xx jar/file txt

To read jar, we have to use a stream to read it, not file, but jar, which I've just spelled out

jar inside the file read mode:


ClassPathResource classPathResource = new ClassPathResource("test.txt");

Get file flow: classPathResource .getInputStream();

conclusion

Above is the paper on web project read classpath path under the file content, hope to help you. Interested friends can continue to refer to other related topics in this site, if there is any deficiency, welcome to comment out. Thank you for your support!


Related articles: