Question: A few days ago, I encountered a problem that required reading file contents from a web application. Generally, configuration files are placed in the project src directory, which is very convenient to read. This is the habit of most people. But this time it happened to be placed in a subdirectory under the WebContent directory. Although I was depressed, the problem still had to be solved. So let’s make a note here.
Solution: XXX.class.getResourceAsStream(Path) to obtain the stream object, you must understand the changes in the directory after deployment
Example:
import java.io.IOException; import java.io.InputStream; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; public class MyListener implements ServletContextListener { @Override public void contextDestroyed(ServletContextEvent arg0) { } @Override public void contextInitialized(ServletContextEvent event) { //指定要读取的文件路径,此处的test.txt放在工程的web目录下面 InputStream is = MyListener.class.getResourceAsStream("/../../web/test.txt"); if(is!=null){ byte []bytes = new byte[1024]; try { while(is.read(bytes)>0){ System.out.println(bytes.toString()); } } catch (IOException e) { e.printStackTrace(); }finally{ if(is!=null){ try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } } } }
The above is the detailed content of How to read resources in WEB applications in Java. For more information, please follow other related articles on the PHP Chinese website!