//////////////////////////////////////////////////////////////////////////////////////////// //PIMS: Personal Invstment Management System //Class : FileDownload //Author: Raghu //This class downloads file from net using proxy // //////////////////////////////////////////////////////////////////////////////////////////// import java.io.*; import java.net.*; import java.util.*; public class FileDownload { FileDownload(){ } public static int readBlocking( InputStream inStream, byte b[], int iOffset,int len ) throws IOException { int totalBytesRead = 0; int bytesRead = 0; while ( totalBytesRead < len && (bytesRead = inStream.read( b, iOffset + totalBytesRead, len - totalBytesRead )) >= 0 ) { totalBytesRead += bytesRead; } return totalBytesRead; } public boolean download( URL url, File fileOut ) { URLConnection uc = null; InputStream inStream = null; FileOutputStream fos = null; if( url == null || fileOut == null ) { return false; } try { uc = url.openConnection(); uc.setAllowUserInteraction( true ); uc.setDoInput( true ); uc.setDoOutput( false ); uc.setUseCaches( true ); uc.connect(); inStream = uc.getInputStream(); fos = new FileOutputStream( fileOut ); return copy( inStream, fos, uc.getContentLength(), true ); } catch (IOException ioe) { return false; } catch(Exception e) { return false; } } public boolean copy ( InputStream inStream, OutputStream outStream, long length,boolean isClosed ) { if ( length <= 0 || inStream == null || outStream == null ) { return false; } try { int blockSize = (int)Math.min( 512, length ); long blocks = length / blockSize; int lastBlock = (int) ( length % blockSize ); byte[] byteArray = new byte[ blockSize ]; for ( long i = 0; i < blocks; i++ ) { int bytesRead = readBlocking( inStream, byteArray, 0, blockSize); if ( bytesRead != blockSize ) throw new IOException(); outStream.write(byteArray); } if ( lastBlock > 0 ) { int bytesRead = readBlocking( inStream, byteArray, 0 , lastBlock ); if ( bytesRead != lastBlock ) throw new IOException(); outStream.write( byteArray, 0 , lastBlock ); } inStream.close(); if ( isClosed ) { outStream.close(); } return true; } catch ( IOException ioe ) { return false; } catch ( Exception e ) { return false; } } }