Issue
As title says, the file is not created when using servlets. I have a simple web application, and I want to take input from the HTML and write them down into a .txt file. 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. 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+");
}
}
Solution
Apparently it creates the file in the Apache Tomcat/bin folder, and not in the project folder. My mistake. Thanks JB Nizet for the help.
Answered By - SwiftCaller