您不能直接从 Java 访问 webapp 中可用的资源。
随着文件从编译时/src/YourClass.java
消失。/WEB-INF/classes/
因此,当您尝试访问BufferedReader br = new BufferedReader(new FileReader("abc.txt"));
.
它根据您给定的示例在 /WEB-INF/classes/abc.txt 中搜索“abc.txt”。
使用servletContext.getRealPath("/");
which 返回您的 Web 应用程序webapps
目录的路径,然后您可以使用此路径访问资源。
注意:返回的路径servletContext.getRealPath("/");
还取决于您如何部署 Web 应用程序。默认情况下,eclipse 使用自己的内部机制来部署 Web 应用程序。
这是关于它应该如何的示例屏幕截图
小服务程序代码:
import java.io.File;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class StaticTestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private ServletContext servletContext;
private String rootPath;
public StaticTestServlet() {
super();
// TODO Auto-generated constructor stub
}
@Override
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
super.init(config);
servletContext = config.getServletContext();
rootPath = servletContext.getRealPath("/");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("In Get and my path: " + rootPath + "documents"); // documents is the direcotry name for static files
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("In Post and my path: " + rootPath + "documents"); // documents is the direcotry name for static files
}
}