本文介绍了如何在Servlet中读取文本文件和输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有文件:input.txt
我想读取此文件,将值放在input.txt的新output.txt中。
i have file: input.txtI want to read this file, put values in new output.txt from input.txt.
Servlet。 java
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为空。出了什么问题?
but output.txt is empty. What's wrong?
推荐答案
Apache FileUtils,可以简化
Apache FileUtils, could make it simple
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);
}
}
这篇关于如何在Servlet中读取文本文件和输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!