File Upload and Download using Java

SHARE & COMMENT :

File Upload and Download is always a handy utility to know. There will be some need to upload a file to an FTP server, Like if you generate a report or store some data in .xls file, then it needs to be uploaded to a FTP server for further use. like wise we need to download some data (data stored in .xls files)for manuplation from the server in our projects. Here we have the code to do this for us. The FileUploadDownload utility.

also readfollow us on @twitter and @facebook

also read:

This file has the two classes one for upload a file to the FTP server and the other one for downloading the file from the FTP server. This program is written in very simple and easy startegy to upload or download the files using Java. It is using BufferedOutputStream and BufferedInputStream IO classes. This program can be effectively reuse for your purpose incase if you want to upload or download the files from your website or your project work. If you like the program and feels it is very useful for you, please write comment and let us know if there is any improvement needed in the code.

If you have any doubts on the code and looking for the help on this code, please post your queries in the comments section.

File Upload and Download Code Example

package com.resource.util;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * This class is used to upload a file to a FTP server.
 *
 * @author Muthu
 */
public class FileUpload
{

   /**
    * Upload a file to a FTP server. A FTP URL is generated with the
    * following syntax:
    * ftp://user:password@host:port/filePath;type=i.
    *
    * @param ftpServer , FTP server address (optional port ':portNumber').
    * @param user , Optional user name to login.
    * @param password , Optional password for user.
    * @param fileName , Destination file name on FTP server (with optional
    *            preceding relative path, e.g. "myDir/myFile.txt").
    * @param source , Source file to upload.
    * @throws MalformedURLException, IOException on error.
    */
   public void upload( String ftpServer, String user, String password,
         String fileName, File source ) throws MalformedURLException,
         IOException
   {
      if (ftpServer != null && fileName != null && source != null)
      {
         StringBuffer sb = new StringBuffer( "ftp://" );
         // check for authentication else assume its anonymous access.
         if (user != null && password != null)
         {
            sb.append( user );
            sb.append( ':' );
            sb.append( password );
            sb.append( '@' );
         }
         sb.append( ftpServer );
         sb.append( '/' );
         sb.append( fileName );
         /*
          * type ==> a=ASCII mode, i=image (binary) mode, d= file directory
          * listing
          */
         sb.append( ";type=i" );

         BufferedInputStream bis = null;
         BufferedOutputStream bos = null;
         try
         {
            URL url = new URL( sb.toString() );
            URLConnection urlc = url.openConnection();

            bos = new BufferedOutputStream( urlc.getOutputStream() );
            bis = new BufferedInputStream( new FileInputStream( source ) );

            int i;
            // read byte by byte until end of stream
            while ((i = bis.read()) != -1)
            {
               bos.write( i );
            }
         }
         finally
         {
            if (bis != null)
               try
               {
                  bis.close();
               }
               catch (IOException ioe)
               {
                  ioe.printStackTrace();
               }
            if (bos != null)
               try
               {
                  bos.close();
               }
               catch (IOException ioe)
               {
                  ioe.printStackTrace();
               }
         }
      }
      else
      {
         System.out.println( "Input not available." );
      }
   }

   /**
    * Download a file from a FTP server. A FTP URL is generated with the
    * following syntax:
    * ftp://user:password@host:port/filePath;type=i.
    *
    * @param ftpServer , FTP server address (optional port ':portNumber').
    * @param user , Optional user name to login.
    * @param password , Optional password for user.
    * @param fileName , Name of file to download (with optional preceeding
    *            relative path, e.g. one/two/three.txt).
    * @param destination , Destination file to save.
    * @throws MalformedURLException, IOException on error.
    */
   public void download( String ftpServer, String user, String password,
         String fileName, File destination ) throws MalformedURLException,
         IOException
   {
      if (ftpServer != null && fileName != null && destination != null)
      {
         StringBuffer sb = new StringBuffer( "ftp://" );
         // check for authentication else assume its anonymous access.
         if (user != null && password != null)
         {
            sb.append( user );
            sb.append( ':' );
            sb.append( password );
            sb.append( '@' );
         }
         sb.append( ftpServer );
         sb.append( '/' );
         sb.append( fileName );
         /*
          * type ==> a=ASCII mode, i=image (binary) mode, d= file directory
          * listing
          */
         sb.append( ";type=i" );
         BufferedInputStream bis = null;
         BufferedOutputStream bos = null;
         try
         {
            URL url = new URL( sb.toString() );
            URLConnection urlc = url.openConnection();

            bis = new BufferedInputStream( urlc.getInputStream() );
            bos = new BufferedOutputStream( new FileOutputStream(
                  destination.getName() ) );

            int i;
            while ((i = bis.read()) != -1)
            {
               bos.write( i );
            }
         }
         finally
         {
            if (bis != null)
               try
               {
                  bis.close();
               }
               catch (IOException ioe)
               {
                  ioe.printStackTrace();
               }
            if (bos != null)
               try
               {
                  bos.close();
               }
               catch (IOException ioe)
               {
                  ioe.printStackTrace();
               }
         }
      }
      else
      {
         System.out.println( "Input not available" );
      }
   }
}

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Comments

  1. Thanks yaar.

  2. Hi,
    How can I do it if I want to UPLOAD to a Web Server? (http)

  3. Hello, Krishna.
    Can you please tell me what happens if the file already exists in the FTP server?

    Oh, thank you for the guide. Twas' really useful.
    I was looking for a guide like tis' one.

  4. Indranil Maiti says:

    Hello Krishna

    Can u plz give a code for text to speech conversion in JAVA

    • Dim msg,sapi
      msg=InputBox(“Enter ur text :”,”Addot text 2 speech converter”)
      Set sapi=CreateObject(“sapi.spvoice”)
      sapi.Speak msg+ “how are u”
      —–paste this code in any text file and give it .vbs extension….

  5. wow!!
    I was searching this for a loooong time, i need to try it soon!

  6. not clear…

  7. how can i upload or download large files such as 5mb from a mobile phone. My code is showing out of memory error

  8. hi… I need to upload a file in server path and again i need to retrieve that file path into URL so that i show the file in jsp page using that converted URL… Suggestions and examples please..

  9. hi,
    thanks for ftp upload code, but, how about sftp upload and download? could java do this without any third party libraries?

  10. Suresh says:

    How to use that upload and download functionality in struts2.Early reply that will be great for me

  11. Hi,
    I need to select multiple check boxes on select i need to download the files of multiple rows…

  12. Ravindra Patil says:

    hi sir this code is helpful but i want the code to implement out of band signaling concept

  13. Srujana Puttagunta says:

    Hi Muthu…

    i want to upload one file from one path to another server , how can i do that, could you kindly reply

    Thanks
    Srujana

  14. Hi Muthu..

    Can you please let me know how to upload file from one remote path to remote server

    Thanks in advance
    Srujana

  15. Rishav kumar says:

    actually i want to upload files in web server and then download it on j2ee.i m getting the problem in downloading the problem.
    for example if user uploads file1 then he will able to download the file1.and then he uploads file2 but then when clicking of download option,it is only downloading file 2,not file1.

  16. Anirban Chakrabarty says:

    Hi Krishna, How r u? R u still with ACC

  17. Hi Krishna,

    I’m facing an issue while uploading a file to a FTP server via URl connection.
    Even after setting the property : conn.setDoOutput(true);
    I’m getting the exception:
    cannot write to a URLConnection if doOutput=false – call setDoOutput(true)

    Please advise!

    Thanks.

Trackbacks

  1. JavaPins says:

    File Upload and Download using Java…

    Thank you for submitting this cool story – Trackback from JavaPins…

Speak Your Mind

*

Close
Please support the site
By clicking any of these buttons you help our site to get better