I want to download a MS Word 2003 document that I am creating with the content myString in it.
I have used the following code:
BufferedReader reader = new BufferedReader(new FileReader(templatePathFilename));
HttpServletResponse response = new MyHttpServletResponse();
response.setContentType ("application/msword");
response.setHeader ("Content-Disposition", "attachment; filename=\""+outgoingFileName);
ServletOutputStream myOut = response.getOutputStream();
myOut.write(myString.getBytes());
myOut.flush();
myOut.close();
But the line myOut.write(myString.getBytes()) gives a NullPointerException.
MyHttpServletResponse is a class that eclipse has produced by default when I quick fix the error generated. Do I need to modify that class?
Can anyone please help!
EDIT: The actual code i am working on is as below:
BufferedReader reader = new BufferedReader(new FileReader(templatePathFilename));
String outgoingFileName = outputPathFilename;
response.setContentType("application/msword");
response.setHeader("Content-Disposition", "attachment; filename="+outgoingFileName);
OutputStream myOut = response.getOutputStream();
try {
String thisLine;
while ((thisLine = reader.readLine()) != null) {
if(thisLine.contains("##"))
{
for (java.util.Enumeration e = FrontSheetMap.keys(); e.hasMoreElements();{
String name = (String) e.nextElement();
String value = FrontSheetMap.get(name).toString();
thisLine= thisLine.replaceAll("##" + name.toUpperCase() + "##", value);
}
}
myOut.write(thisLine);
myOut.write("\n");
}
myOut.flush();
}catch(Exception e){}
The while loop replaces the placeholders in the input file with required values and the new content in thisLine is to be written on the output file. I need a download option which pops up on clicking the link which executes this code.
As you mentioned
MyHttpServletResponseis a class that eclipse has produced by default when I quick fix the error generated, that seems to be the problem.Your code should be inside some servlet/JSP and the HttpServletResponse object should be taken from the container (which is passed to service/doGet/doPost methods).
What you are using is a default/dummy implementation of
HttpServletResponsewhich givesresponse.getOutputStream();as null. If you use the container provided objects, your problem will be solved.