java访问URL并下载文件

本文介绍了一个 Java 类 TestSampleAnalysisReport,该类提供了一个静态方法 saveToFile,用于通过给定的 URL 下载文件并保存到指定路径。此方法使用 HttpURLConnection 和 BufferedInputStream 实现了基本的网络文件下载功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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();
  }
 }

}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值