[英]Can't create text file when using Servlets
As title says, the file is not created when using servlets. 如标题所示,使用servlet时不会创建文件。 I have a simple web application, and I want to take input from the HTML and write them down into a .txt file. 我有一个简单的Web应用程序,我想从HTML中获取输入并将它们写到.txt文件中。 The problem is that, everything runs good, and I don't get any error or exception, it just doesn't create the text file. 问题是,一切运行良好,并且我没有收到任何错误或异常,只是没有创建文本文件。 I took the same code (for creating the text file) and I tested it into a separate class and it works perfectly. 我使用了相同的代码(用于创建文本文件),并将其测试到一个单独的类中,并且效果很好。 The problem is when I try to create a text file in the servlet. 问题是当我尝试在servlet中创建文本文件时。 This is my code: 这是我的代码:
@WebServlet("/home")
public class HomePage extends HttpServlet
{
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.sendRedirect("/home.html");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String add = request.getParameter("buttonAdd");
String read = request.getParameter("buttonRead");
String update = request.getParameter("buttonUpdate");
String delete = request.getParameter("buttonDelete");
if(add != null)
{
String title = request.getParameter("dvd_title");
String year = request.getParameter("dvd_year");
String price = request.getParameter("dvd_price");
if(!title.equals("") && !year.equals("") && !price.equals(""))
{
if(!Character.isDigit(title.charAt(0)))
{
if (isNumeric(year) && isNumeric(price))
{
try
{
List<String> lines = Arrays.asList("Title: " + title, "Year: " + year, "Price: " + price);
Path file = Paths.get("DVD - " + title + ".txt");
Files.write(file, lines, Charset.forName("UTF-8"));
}
catch(IOException e)
{
e.printStackTrace();
}
}
else
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("Year and price must be numbers");
}
}
else
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("Title cannot start with a number");
}
}
}
if(read != null)
{
System.out.println("2");
}
if(update != null)
{
System.out.println("3");
}
if(delete != null)
{
System.out.println("4");
}
}
private static boolean isNumeric(String s)
{
return s != null && s.matches("[-+]?\\d*\\.?\\d+");
}
}
Apparently it creates the file in the Apache Tomcat/bin folder, and not in the project folder. 显然,它在Apache Tomcat / bin文件夹中而不是在项目文件夹中创建文件。 My mistake. 我的错。 Thanks JB Nizet for the help. 感谢JB Nizet的帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.