virat
virat

Reputation: 13

How to write to a txt file in Servlet and automatically download it when requests

I want to create a txt file in my Servlet and automatically download it at the client side when client requests. I have below code to write to a txt, but it gives access denied error in Netbeans IDE using glassfishserver. How can I do it?

 //File creation
 String strPath = "C:\\example.txt";
 File strFile = new File(strPath);
 boolean fileCreated = strFile.createNewFile();
 //File appending
 Writer objWriter = new BufferedWriter(new FileWriter(strFile));
 objWriter.write("This is a test");
 objWriter.flush();
 objWriter.close();

Upvotes: 0

Views: 4280

Answers (1)

Shafin Mahmud
Shafin Mahmud

Reputation: 4081

Its not a thing you do it in JSP. You better have a Servlet and just create a Outputstream and put your text in it. Then flush that stream into the HttpServletResponse.

@WebServlet(urlPatterns = "/txt")
public class TextServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/plain");
        response.setHeader("Content-Disposition", "attachment; filename=\"example.txt\"");
        try {
            OutputStream outputStream = response.getOutputStream();
            String outputResult = "This is Test";
            outputStream.write(outputResult.getBytes());
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Remember you need to set the content-type text/plain and a Content-Disposition header that mentions filename and tells broswer that it should be downloaded as file attachment.

This is what Content-Disposition header is about in concise description

In a regular HTTP response, the Content-Disposition response header is a header indicating if the content is expected to be displayed inline in the browser, that is, as a Web page or as part of a Web page, or as an attachment, that is downloaded and saved locally.

If you are a beginner. You may like to learn more about from this

Upvotes: 1

Related Questions