下载文件(工具类)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chaoyue1861/article/details/83062184

一、


import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.zip.GZIPInputStream;

public class filesDownloadUtils {

	/**
	 * 文件下载
	 * 
	 * @param getUrlString
	 *            获取文件路径
	 * @param loadUrlString
	 *            下载文件路径
	 */
	public static void download(String getUrlString, String loadUrlString) throws Exception {

		URL url = new URL(getUrlString);// 构造url
		URLConnection conn = url.openConnection();// 打开连接
		conn.setConnectTimeout(5 * 1000); // 设置请求超时为5s
		InputStream is = conn.getInputStream();// 输入流
		String code = conn.getHeaderField("Content-Encoding");
		if (code != null && code.equals("gzip")) {// 压缩
			GZIPInputStream gis = new GZIPInputStream(is);
			byte[] by = new byte[1024];// 1k的数据缓冲
			int len;// 读取到的数据长度
			OutputStream os = new FileOutputStream(loadUrlString);// 输出的文件流
			while ((len = gis.read(by)) != -1) {
				os.write(by, 0, len);
			}
			// 关闭所有连接
			os.close();
			gis.close();
			is.close();
		} else {
			byte[] by = new byte[1024];// 1k的数据缓存
			int len;// 读取到的数据长度
			OutputStream os = new FileOutputStream(loadUrlString);// 输出的文件流
			while ((len = is.read(by)) != -1) {
				os.write(by, 0, len);
			}
			// 关闭所有连接
			os.close();
			is.close();
		}
	}

}

二、

import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.URL;

public class filesDownloadUtils {

	/**
	 * 文件下载
	 * 
	 * @param getUrlString
	 *            获取文件路径
	 * @param loadUrlString
	 *            下载文件路径
	 */
	public static void download(String getUrlString, String loadUrlString,HttpServletResponse response) throws Exception {

                File sourceFile = new File(getUrlString);
                if(!sourceFile.exists()){
                    throw new Exception("您下载资源不存在");
                }
		URL url = new URL(getUrlString);// 构造url
		DataInputStream dis = new DataInputStream(url.openStream());// 打开网络输入流
		File file = new File(loadUrlString);
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/octet-stream");
		FileOutputStream fos = new FileOutputStream(file);// 建立一个新的文件
		byte[] by = new byte[1024];// 1k的数据缓冲
		int len;// 获取文件的长度
		while ((len = dis.read()) != -1) {
			fos.write(by, 0, len);
		}
		fos.close();
		dis.close();

	}

}

猜你喜欢

转载自blog.csdn.net/chaoyue1861/article/details/83062184