`

JAVA 实现HTTP下载

    博客分类:
  • JAVA
阅读更多

  public static void getRemoteFile( String urlStr, String fileName )
        throws IOException, InterruptedException
    {
        byte[] buffer = new byte[1024];
        HttpURLConnection connection = null;
        URL url = null;
        BufferedInputStream bis = null;
        FileOutputStream fos = null;
        int size=0;
        int contentSize = 0;
        int downloaded = 0;
        
        if( null == urlStr || null == fileName )
        {
            return;
        }
        try
        {
            url = new URL( urlStr );
            connection = ( HttpURLConnection ) url.openConnection();

            bis = new BufferedInputStream( connection.getInputStream() );

            contentSize = connection.getContentLength();
            if( contentSize <= 0 )
            {
                return;
            }
            fos = new FileOutputStream( fileName );
            //read the file and write to local file(filename)
            while ((size=bis.read( buffer ))!=-1)
            {
                fos.write( buffer,0, size);
                fos.flush();
                downloaded = downloaded + buffer.length;
                System.out.println( "Downloaded: " + downloaded + " bytes!" );
            }
        }
        catch ( IOException e )
        {
            throw e;
        }
        finally
        {
            try
            {
                //close the connections and streams
                fos.close();
                bis.close();
                connection.disconnect();
            }
            catch ( IOException e1 )
            {
                throw e1;
            }
        }
    }
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics