代码运行良好,直到我在我的servlet程序中包含了读取文本文件的代码。实际上我需要读取文本文件并使用正则表达式模式匹配必须在文本文件中搜索模式。我尝试了很多,但我无法弄清楚。每次我使用localhost运行它都会直接进入catch,在我把try-catch放到error:500 file not found "database.txt"
之前,而database.txt
与我的servlet程序webapps/myprogram/database.txt
在同一个地方。我正在使用tomcat8。请帮助我,为什么它没有得到文件并进入捕获..
这是我的servlet程序:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JOptionPane;
import java.io.*;
/**
* @author hp
*/
@WebServlet(urlPatterns = {"/servlet1"})
public class servlet1 extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String txt = request.getParameter("query");
try {
FileInputStream fstream = new FileInputStream("database.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
if (txt.matches("Who is the(.*)")) {
String re1 = ".*?";
String re2 = "(?:[a-z][a-z]+)";
String re3 = ".*?";
String re4 = "(?:[a-z][a-z]+)";
String re5 = ".*?";
String re6 = "(?:[a-z][a-z]+)";
String re7 = ".*?";
String re8 = "((?:[a-z][a-z]+))";
String re9 = ".*?";
String re10 = "(?:[a-z][a-z]+)";
String re11 = ".*?";
String re12 = "((?:[a-z][a-z]+))";
Pattern p =
Pattern.compile(re1 + re2 + re3 + re4 + re5 + re6 + re7 + re8 + re9 + re10 + re11 + re12, Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
Matcher m = p.matcher(txt);
if (m.find()) {
String word1 = m.group(1);
String word2 = m.group(2);
String z = word2.toString() + "&&" + word1.toString() + "&&" + "name.*" + "\n";
while ((strLine = br.readLine()) != null) {
if (Pattern.matches(z, strLine)) {
Pattern pattern = Pattern.compile("'(.*?)'");
Matcher matcher = pattern.matcher(strLine);
if (matcher.find()) {
String a = matcher.group(1);
request.setAttribute("a", a);
request.getRequestDispatcher("/output.jsp").forward(request, response);
}
}
}
}
} else {
String z = "Sorry......Invalid query !!!";
request.setAttribute("z", z);
request.getRequestDispatcher("/output.jsp").forward(request, response);
}
} catch (Exception e) {
throw new ServletException(e);
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//processRequest(request, response);
doGet(request, response);
}
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
&#13;
答案 0 :(得分:0)
如果你的文件在web root中(我假设你是),那么你必须使用ServletContext.html#getRealPath(java.lang.String)这将为你提供文件的实际路径。因此,您创建FileInputStream
的代码应为。
FileInputStream fstream =
new FileInputStream(getServletContext().getRealPath("/database.txt"));