i have file: input.txt I want to read this file, put values in new output.txt from input.txt.
Servlet.java
protected void processRequest(HttpServletRequ
Try following code
input.txt
should be present in the root directory of your application
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();
}
}
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);
}
}