问题描述
我在Java中有这个servlet代码:
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;
}
}
此BufferedReader br = new BufferedReader(new FileReader(filename));
始终显示没有吮吸文件,但我将其放在ProjectName/web/Web-INF/文件夹中.我如何从该文件读取或获取正确的路径?
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 /
)
第二个FileReader不是在Web应用程序中加载资源的正确方法,如果不提取应用程序之争怎么办?它仍然会失败.
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.
您应使用 ServletContext#getResourceAsStream 以获得 InputStream 并使用它来读取您的资源.
You should use ServletContext#getResourceAsStream to get an InputStream and use it to read your resource.
这篇关于Java Servlet,将数据从文本文件写入网页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!