File Upload and Download using Java

October 10, 2007

Java

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.

This fille 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.

also readfollow us on @twitter and @facebook

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" );
      }
   }
}
email

Comments

comments

  • ashu

    Thanks yaar.

    • suthukrish

      HI Ashu,

      Thank you for the comments!!
      How are you finding this code useful? If you have any doubts, please post it here.

      Thanks,
      Krishna

      • Ashutosh Gangrade

        No suthukrish , I don't have any doubt regarding this code.Its really helpful for me.
        Can you please help me write code from downloading a file from secure HTTP server?
        Please reply me ASAP. I urgently need this.

        • suthukrish

          Hello Ashutosh,

          Thank you for the comments. There is new article on downloading the file, also it has the code snippet for downloading from the HTTPS server. Please try it and let us know if its is working.
          http://www.javabeat.net/examples/2012/04/13/downl

          Thanks,
          Krishna

      • Ashutosh Gangrade

        Please help me to write a code for downloading a file from secure HTTP server with user credentials.

    • satish4ru

      Hi ..

      I am trying to upload file using ftp api . But i need to change the file name that i uploaded in server . Is it possible please help me..

  • daniel

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

  • Felipe

    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.

  • Indranil Maiti

    Hello Krishna

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

    • AD

      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….

  • Pingback: JavaPins

  • http://www.facebook.com/profile.php?id=716774105 Israel García Herrera

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

    • Krish

      Hi,

      Thank you for reading our blog.
      Try this and let us know if it’s working.

      • http://www.facebook.com/profile.php?id=716774105 Israel García Herrera

        You know, it would be very very helpful if you also explain how to set up a FTP server in a Desktop PC.

        However this Blog is amazing.

        • Krish

          Thank you for the suggestion. We would try that example soon

          • http://www.facebook.com/profile.php?id=716774105 Israel García Herrera

            hey Krish, i have an issue with the code, Java is sending an exception… something about “the connection has been reset”.. can u help me with this?

      • satish4ru

        Hi krish,
        I am trying to upload file using ftp api . But i need to change the file name that i uploaded in server . Is it possible please help me..

  • siddhu

    not clear…

  • ove

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

  • Suresh

    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..

  • sam

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