首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

JAVA 实现HTTP上载

2012-12-21 
JAVA 实现HTTP下载public static void getRemoteFile( String urlStr, String fileName )throws IOExcepti

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

热点排行