java下载网络文件_java下载网络文件的方法有哪些

本文介绍了两种在Java中下载网络文件的方法:一是使用Apache的FileUtils工具包,二是通过字节流方式实现。每种方法都包含了设置超时、防止403错误的User-Agent头以及文件保存的相关步骤。
摘要由CSDN通过智能技术生成

5cff9662ee799e4e041deb528e9b9f0d.png

下载网络文件的方法有:字节流下载

apache的FileUtils工具包下载

NIO下载

实现代码如下:package com.dsp.rpc.metricelf;

import org.apache.commons.io.FileUtils;

import java.io.File;

import java.net.HttpURLConnection;

import java.net.URL;

public class DownloadZipUtil {

/**

* FileUtils下载网络文件

*

* @param serverUrl :网络文件地址

* @param savePath:本地保存路径

* @param zipSavePath :压缩文件保存路径

* @return

*/

public static String downloadFile(String serverUrl, String savePath, String zipSavePath) throws Exception {

String result;

File f = new File(savePath);

if (!f.exists()) {

if (!f.mkdirs()) {

throw new Exception("makdirs: '" + savePath + "'fail");

}

}

URL url = new URL(serverUrl);

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setConnectTimeout(3 * 1000);

//防止屏蔽程序抓取而放回403错误

conn.setRequestProperty("User-Agent", "Mozilla/4.0(compatible;MSIE 5.0;Windows NT;DigExt)");

Long totalSize = Long.parseLong(conn.getHeaderField("Content-Length"));

if (totalSize > 0) {

FileUtils.copyURLToFile(url, new File(zipSavePath));

result = "success";

} else {

throw new Exception("can not find serverUrl :{}" + serverUrl);

}

return result;

}

/**

* 字节流下载压缩文件

* @param serverUrl :网络地址

* @param savePath :保持路径

* @param zipSavePath :压缩文件保持路径

* @return :下载结果

* @throws Exception :异常

*/

public static String downloadZip(String serverUrl,String savePath,String zipSavePath) throws Exception{

String result = "fail";

File f = new File(savePath);

if(!f.exists()){

if (!f.mkdirs()) {

throw new Exception("makdirs: '" + savePath + "'fail");

}

}

//Sardine是WebDAV的工具包

Sardine sardine = SardineFactory.begin("test","test");

if(sardine.exists(serverUrl)){

URL url = new URL(serverUrl);

URLConnection conn = url.openConnection();

int length = conn.getContentLength();

conn.setConnectTimeout(3 * 1000);

// 防止屏蔽程序抓取而返回403错误

conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

InputStream is = sardine.getInputStream(serverUrl);

BufferedInputStream bis = new BufferedInputStream(is);

FileOutputStream fos = new FileOutputStream(zipSavePath);

BufferedOutputStream bos = new BufferedOutputStream(fos);

int len;

byte[] bytes = new byte[length/5];

while ((len = bis.read(bytes)) != -1) {

bos.write(bytes, 0, len);

}

//清除缓存

bos.flush();

//关闭流

fos.close();

is.close();

bis.close();

bos.close();

result = "success";

}else {

throw new Exception("can not find file");

}

return result;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值