简体   繁体   中英

Java servlets, write data from text file to web page

I have this servlet code in java:

package servlets;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import java.net.*;


public class Servlet1 extends GenericServlet{
 private ServletConfig sc;
 public void init(ServletConfig conf) throws ServletException{
     super.init(conf);
     sc = conf;
 }

 public void read_file(){
     String filename = "/web/WEB-INF/Data.txt";
     BufferedReader br = new BufferedReader(new FileReader(filename));
     // Why this doesn't work ?

 }

 public void service(ServletRequest req, ServletResponse resp) throws ServletException,IOException{   
     resp.setContentType("text/html; charset=windows-1251");
     PrintWriter pw = resp.getWriter();
     pw.println("<html><head>");
     pw.println("<title>sdasdasda</title>");
     pw.println("</head><body><h2>Servlet information</h2>");
     pw.println("Servlet name - "+sc.getServletName()+ "<br>");
     pw.println("Servlet parametrs: <br>");
     //pw.println(read_file());
     Enumeration names = sc.getInitParameterNames();

     while(names.hasMoreElements()){
        String name = (String)names.nextElement();
        pw.print(name + ": ");
        pw.println(sc.getInitParameter(name)+"<br>");
     }
     pw.println("</body></html>");
     pw.flush();
     pw.close();
 }
 public void destroy(){
     sc = null;
 }

}

And this BufferedReader br = new BufferedReader(new FileReader(filename)); always shows that there is no suck file, but I put it in ProjectName/web/Web-INF/ folder. How do i read from this file, or get the right path to it ?

First of all you are specifying an absolute path (your path starts with / )

Second FileReader is not the correct way of loading a resource in a web application, what is if your application war is not extracted? It will still fail.

You should use ServletContext#getResourceAsStream to get an InputStream and use it to read your resource.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM