Home > Java > javaTutorial > How to read resources in WEB applications in Java

How to read resources in WEB applications in Java

WBOY
Release: 2023-05-01 13:52:17
forward
901 people have browsed it

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();                      }                  }              }          }      }   }
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template