java访问URL并下载文件

来源:互联网 发布:淘宝客服要注意的事项 编辑:程序博客网 时间:2024/05/23 18:31

package com.xxxx.service;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 *
 *  java访问URL并下载文件
 * 用于从总管理中心访问分析系统,拿到分析报告;
 * @author  xxx  2015-01-19
 *
 */
public class TestSampleAnalysisReport {
 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://xxxxxxx:8081/tasks/download/1", "d:\\111.doc");
   System.out.println("end");
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

}

0 1