Here’s a servlet code example to download a text file from a website.

For example

Let’s say a text file named “testing.txt” , and you want to let user download it with a URL , for example “http://localhost:8080/servlet/DownloadDemo” .

1. Create a text file named “testing.txt” , put it into the project root folder.

\--servlet (project root folder)
      \--testing.txt (download file here)

2. Servlet code

package com.mkyong;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletDownloadDemo extends HttpServlet{
  private static final int BYTES_DOWNLOAD = 1024;
  public void doGet(HttpServletRequest request, 
   HttpServletResponse response) throws IOException{
	ServletContext ctx = getServletContext();
	InputStream is = ctx.getResourceAsStream("/testing.txt");
	int read=0;
	byte[] bytes = new byte[BYTES_DOWNLOAD];
	OutputStream os = response.getOutputStream();
	while((read =!= -1){
		os.write(bytes, 0, read);
The “getResourceAsStream()” method with a forward slash (“/”), which represent the root of your web application.

3. Web deployment descriptor

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="" 

4. Compiled it and copy to the Tomcat folder

               \-- testing.txt (download file)

4. Done , access URL http://localhost:8080/servlet/DownloadDemo , it will prompts user to download the text file automatically.

You may interest this file download example in Struts 1.x
Tags :
Founder of, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.
My website is hosted by Liquid Web, I really like their fast and helpful support, it saved me a lot of time. Furthermore, their servers are extremely reliable, fast and stable, I don't remember when was the last time we had server downtime. Btw, they're offering $100 Coupon now, if you are sourcing for great hosting provider, go grab it.

Related Posts

Popular Posts