`
happyqing
  • 浏览: 3152001 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

java访问URL并下载文件

阅读更多

 

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
/**
 * java访问URL并下载文件
 * @author yangjuqi 2007-12-14 下午04:08:51
 *
 */
public class nn1 { 

 public static void saveToFile(String destUrl, String fileName) throws IOException {   
              FileOutputStream fos = null;   
             BufferedInputStream bis = null;   
              HttpURLConnection httpUrl = null;   
              URL url = null;   
              byte[] buf = new byte[1024];   
              int size = 0;   
                 
              url = new URL(destUrl);   
              httpUrl = (HttpURLConnection) url.openConnection();   
              httpUrl.connect();   
              bis = new BufferedInputStream(httpUrl.getInputStream());   
              fos = new FileOutputStream(fileName);   
              while ((size = bis.read(buf)) != -1)   
                  fos.write(buf, 0, size);   
              fos.close();   
              bis.close();   
              httpUrl.disconnect();   
          }  


 public static void main(String[] args) {
  try {
   System.out.println("begin");
   saveToFile("http://........","f:\\111.rar");

   System.out.println("end");
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
} 

 

更稳定的方法

HttpClient 3.1下载文件

http://happyqing.iteye.com/blog/2089621

HttpClient 4.1 下载文件

http://happyqing.iteye.com/blog/2089627

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics