为什么输出没有打印在Servlet的WEB-INF文件夹下名为EmailList.txt的文件中

这是我的servlet类,负责从HTML页面获取数据并将该数据存储在WEB-INF目录下的EmailList.txt文件中:

Servlet类的代码片段……

//Get Parameters from the request object String firstName=request.getParameter("firstName"); String lastName=request.getParameter("lastName"); String emailId=request.getParameter("emailId"); //Get a relative file name ServletContext context=getServletContext(); String path=context.getRealPath("WEB-INF/EmailList.txt"); //Use Regular Java object to write the data to the file UserData userData=new UserData(firstName, lastName, emailId); UserIO.addUser(userData, path); 

UserData是具有settergetter的常规Java类, UserIO包含用于将内容写入EmailList.txt文件的代码

UserIO类的代码如下:

 public class UserIO { public static void addUser(UserData userData, String filePath) throws IOException { File file=new File(filePath); PrintWriter out=new PrintWriter(new FileWriter(file, true)); out.println(userData.getFirstName()+"\t" + userData.getLastName()+"\t" + userData.getEmailId()); out.close(); } } 

右键单击eclipse中的文件转到属性,你会看到这是一个不同的文件。

实际上你不应该尝试在这样的位置编写/创建文件。 您的应用程序可能无法始终从.war存档中解压缩,在这种情况下, ServletContext#getRealPath()将返回null

另一种方法是在web.xml中定义上下文init参数 ,并为应用程序可见的文件系统设置根目录

  fsroot E:\CodePractice  

并在应用程序中的任何位置(servlet / JSP)检索它,您可以使用ServletContext#getInitParameter(java.lang.String)

 String path = getServletContext().getInitParameter("fsroot");