读书人

JAVA 实现HTTP上载

发布时间: 2012-12-21 12:03:49 作者: rapoo

JAVA 实现HTTP下载

  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;            }        }    }
?

读书人网 >编程

热点推荐