Using a java.net.HttpURLConnection to download the file.


/**
 * This method is used to acutally download the file from a given HttpURLConnection.
 * Both the input and output streams are set up and the file is downloaded from 
 * the URL connection @param huc is the HttpURLConnection from where the file will be
 * retrieved from @param downloadFile is the name of the file to be downloaded.
 */
public static void downloadFile(HttpURLConnection huc, String downloadFile)
  throws IOException
{
  // initialize local vars
  int dataread = 0;
  int count = 0;
  int CHUNK_SIZE = 8192;                   // TCP/IP packet size
  byte[] dataChunk = new byte[CHUNK_SIZE]; // byte array for storing temporary data. 

  // Check for valid MIME type (only retrieve jars, text and gifs)
  String mimeType = huc.getContentType();
  if ( ! ( mimeType.equals("application/java-archive") || 
       mimeType.equals("text/plain") || 
       mimeType.equals("image/gif") )
    )
    throw new IOException("file (" + downloadFile + ") is wrong MIME type: " + mimeType);

  // create file and stream to write the file (throws IOException)
  File destinationFile = new File( PC_DOWNLOADDIR + downloadFile );
  FileOutputStream fos = new FileOutputStream(destinationFile);
  BufferedOutputStream bos = new BufferedOutputStream(fos);

  // receive the file using a BufferedReader
  BufferedInputStream bis = new BufferedInputStream(huc.getInputStream());
  InputStreamReader isr = new InputStreamReader( bis );
  BufferedReader br = new BufferedReader( isr );

  // do the actual download and let the user know of the status
  System.out.print("Downloading " + downloadFile);
  while (dataread >= 0)
  {
    count++;
    dataread = bis.read(dataChunk,0,CHUNK_SIZE);
    System.out.print(".");
    // only write out if there is data to be read
    if ( dataread > 0 )
      bos.write(dataChunk,0,dataread);
  }
  System.out.println(count*CHUNK_SIZE + " bytes done.");

  // don't forget to close the streams
  bis.close();
  bos.close();
}

Featured

Upcoming Events

AppTrends

Sign up for our newsletter.

I agree to this site's Privacy Policy.