我有文件:input.txt 我想读取这个文件,将值放在input.txt的新output.txt中。
Servlet.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/plain");
response.setHeader("Content-Disposition",
"attachment;filename=output.txt");
PrintWriter out = response.getWriter();
ServletContext cntxt = this.getServletContext();
String fName = "/input.txt";
InputStream ins = cntxt.getResourceAsStream(fName);
try {
if(ins != null){
InputStreamReader isr = new InputStreamReader(ins);
BufferedReader reader = new BufferedReader(isr);
int n = 0;
String word ="";
while((word= reader.readLine())!= null)
{
n = Integer.parseInt(word);
out.println(n);
}
} finally {
out.close();
}
}
但是output.txt为空。怎么了?
答案 0 :(得分:0)
尝试以下代码
input.txt
应出现在应用程序的根目录中
protected void processRequest(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
response.setContentType("text/plain");
response.setHeader("Content-Disposition", "attachment;filename=output.txt");
PrintWriter out = response.getWriter();
ServletContext cntxt = this.getServletContext();
String fName = "/input.txt";
InputStream ins = cntxt.getResourceAsStream(fName);
try {
if (ins != null) {
InputStreamReader isr = new InputStreamReader(ins);
BufferedReader reader = new BufferedReader(isr);
int n = 0;
String word = "";
while ((word = reader.readLine()) != null) {
n = Integer.parseInt(word);
out.println(n);
}
}
}finally {
out.close();
}
}
答案 1 :(得分:0)
Apache FileUtils,可以简化
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
List<String> lines = FileUtils.readLines(new File("file.txt), "UTF-8");
for (String line : lines) {
out.println(line);
}
}