문제

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top