JDK中http协议下载文件简单示例

来源:互联网 发布:中国联合网络通信公司 编辑:程序博客网 时间:2024/05/16 05:57
 http协议下载文件代码:
  1. public class HttpDownload {
  2.     private final int  BUF_SIZE = 8096;
  3.     
  4.     private String strUrl = null;
  5.     
  6.     private String localFile = null;
  7.     
  8.     private String localDir = null;
  9.     
  10.     private URL url = null;
  11.     
  12.     private HttpURLConnection httpConn = null;
  13.     
  14.     private boolean debug = true;
  15.     
  16.     public HttpDownload() {
  17.         
  18.     }
  19.     
  20.     public HttpDownload(String url, String file, String dir) throws IOException {
  21.         strUrl = url;
  22.         localFile = file;
  23.         localDir = dir;
  24.         init();
  25.     }
  26.     
  27.     private void init() throws IOException {
  28.         url = new URL(strUrl);
  29.         httpConn = (HttpURLConnection)url.openConnection();
  30.     }
  31.     
  32.     public void download() throws IOException   {
  33.         BufferedInputStream bis = null;
  34.         FileOutputStream fos = null;
  35.         int size = 0;
  36.         byte[] buf = new byte[BUF_SIZE];
  37.         httpConn.connect();
  38.         bis = new BufferedInputStream(httpConn.getInputStream());
  39.         fos = new FileOutputStream(localDir + File.separator + localFile);
  40.         if (debug) {
  41.             System.out.println("retreiving the file");
  42.         }
  43.         System.out.println("starting download.");
  44.         while((size = bis.read(buf)) != -1) {
  45.             fos.write(buf, 0, size);
  46.         }
  47.         fos.close();
  48.         bis.close();
  49.         httpConn.disconnect();
  50.         System.out.println("download finish.");
  51.     }
  52.   

原创粉丝点击