This article mainly studies the problem of reading files under the classpath path under the web project, as follows.
First, we divide it into two categories and classify it by web containers
One is an ordinary web project, such as using the Tomcat container, which is characterized by the compressed package being decompressed into a folder as the container is started. When the project is accessed, it is actually accessing the folder, not the jar or war package.
This is the method of getting the path this.getClass().getResource("/")+fileName
Method to get stream this.getClass().getResourceAsStream(failName);
import org.springframework.util.ResourceUtils;File file= ResourceUtils.getFile("classpath:test.txt");or
ClassPathResource classPathResource = new ClassPathResource("test.txt"); Get the file: classPathResource .getFile();
Get file stream: classPathResource .getInputStream();
The second type is embedded web container, which has a characteristic that there is only one jar file, which will not be decompressed after the container is started, and the jar package or war package is used when the project is actually accessed.
This kind of pitfall is the most likely to encounter pitfalls. The biggest pitfall is that it is read in the first way, debugging locally, running perfectly, and not in the Linux environment.
First, use the method of obtaining the path this.getClass().getResource("/")+fileName to obtain the flow method this.getClass().getResourceAsStream(failName);
When running locally, the cliff can be found, and you print out the path. Yes, it is our eclipse working directory and project directory, but in the target directory.
Now let you analyze why you go online, it's GG. It's very simple. For online embedded projects, we will only put a jar file on it. I understand that the path in the jar cannot be obtained. The jar is a closed thing. Unlike folders, it can't be c:/home/xx.jar/file.txt
Reading files in jars, we can only use streams to read, not file, the file must involve the path. I have just spelled out the path of jar
How to read files in jar:
ClassPathResource classPathResource = new ClassPathResource("test.txt"); Get file stream: classPathResource .getInputStream();
Summarize
The above is the entire content of this article about reading the files under the classpath path in web projects. I hope it will be helpful to everyone. Interested friends can continue to refer to other related topics on this site. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!