Servlet code to download text file from website – Java

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 :

About the Author

Founder of and, 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.


  • Pingback: Artist()

  • Pingback: helpful resources()

  • Pingback: Pirater un Compte Facebook()

  • Pingback: Dan Pompilio()

  • Pingback: the printing house()

  • Pingback: Comment Avoir des Gemmes illimité Clash of Clans()

  • Pingback: psn plus gratuit()

  • Pingback: Make merits()

  • Pingback: screen replacing()

  • Pingback: anti aging beauty tips()

  • Pingback: Looid()

  • Pingback: nasa()

  • Pingback: Durban hotels North beach()

  • Pingback: Thailand pills()

  • Pingback: 411 PAIN()

  • Pingback: TV Wall Install IL()

  • Pingback: Plainview Car Shipping()

  • Pingback:

  • Pingback: Holzbearbeitungsmaschinen Auktionen()

  • Pingback: Google()

  • Jay Poojara

    Your tutorials help me a lot…. Thank u….

  • Ajay

    I have a code like:

    String recommendedFilename = getLocalEntityName();
    response.setHeader(“Content-Disposition”, “attachment; filename=” + recommendedFilename);

    But the when filename (the value for recommendedFilename) contains japanese characters, then the default filename in the “Open/Save” dialogue is not proper japanese. All the japanese characters are coming as junk. Can you please help?

  • Beaver County PA dui attorney

    Designer drugs/herbal remedies and driving
    under the influence of intoxicants?

  • saket

    works fine ,thanks for sharing ,one query i have is that “InputStream is” should be closed or not? because at my end i am not able to delete the file latter since JVM still has it open mode, in my code i have opened a scriplet in jsp and put the above code in it.

  • ravi

    tanq very much :)

    but how to make my browser ask me to download the file ?

  • debra

    I am truly thankful to the holder of this web page who has shared this
    impressive post at at this time.

  • sunny


    I am getting NullPointerException at please help me in this regard.

  • sandeep

    Thanks the code is working but I want to know if we want to get put an anchor in html file and by clicking we start download how to retrieve the name from anchor link…pls help

  • temp

    You saved my life again. Thank you.

  • raja

    hi mkyong,

    i have a small requirement in downloading file from linux, can you tel me how to do….

  • j0n

    do you know if it’s possible to download the file in a specific directory (specified by the servlet) without asking anything to the user?

  • waynegomez

    hahaha I didnt even get what extention I should save these files into or where I should put it to..

  • Alessandro

    thanks a lot for this post

    but in need something different…

    I want that the text file is showed in the browser and not downloaded,
    what is the change that i have to do in the code?


  • tirupathi rao

    where i have to place class file? how to get com.mkyong package?

  • Pingback: Report 2?? Project | Vaniazig's Blog()

  • Sula

    Someone necessarily help to make critically articles I might state. That is the very first time I frequented your web page and to this point? I surprised with the research you made to create this actual publish amazing. Fantastic job!

  • John

    I have a situation where i have created my PDF file in a servlet using bytearrayoutputstream. When run on its own the servlet does work and produces my PDF file, however, it is an instance where i need the file to be opened from a JSP on a button commmand. Is anyone familiar with how I would go about that?

  • kaja

    i’m using jBoss server so can any one help me for that…

    • mkyong

      Servlet is standard, it should work in jboss.

      • deepak

        If u dont know then please dont try to send wri=ong data

  • San Diego Lawyer

    Great article! Thanks a lot

  • Prefabrik

    Thanks for posting such a useful example.

  • Tom

    My name is Ming. I am a student at GSU. I find th eprogram very useful but I’d like to ask the author and other forum members a question regarding download a PDF file to my pc. I’d like to know if this program works for download PDF file to my pc ? Thanks in advance.

    • mkyong

      yes, the concept is apply to any file type, but you may need just change the “response.setContentType(“text/plain”);” to “application/octet-stream” or other content type to suit your need.

      • Praveen

        Thank you, for the note. If the text file have space padding between the text then if we use “text/plain” content type and download a file,all the space padding reduced to single space. And if we use “application/octet-stream” then space padding will remain intact.

  • plaj bayra??

    really good information thanks admin

  • Download

    Thanks Nice Post. I added this thread to favorites.

  • kezia

    what is package com.mkyong? and where can i download it?
    can it used to open a web browser with java program?


  • shravan

    Thanks for posting such a useful example.

  • rsingh

    Yor this code is not working for me it just creates the file but the contents are not downloading……
    Plz reply as soon as possible
    Thanks in Adv.

    • mkyong

      The code is well tested, why not sharing your code, may be something wrong in your code?

  • Tyson F. Gautreaux

    Websites RSS feed is not work in my browser (google chrome) how can I mend it?

  • Pingback: How to download file from website- Java / Jsp | Java()