当前位置 : 主页 > 编程语言 > c++ >

从网页中下载文件到本地 工具类

来源:互联网 收集:自由互联 发布时间:2021-06-30
FileDownloaderUtil.java import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.util.Date;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.
FileDownloaderUtil.java
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

/**
 * 描述:从网页下载文件到本地
 * @param url 需要下载的URL
 * @param savePath 文件保存的路径
 * @param fileName 文件名
 * @param suffixName 文件后缀
 * @author lizheng
 */
public class FileDownloaderUtil implements Runnable {
	/** 需要下载的文件URL */
	private String url ;
	/** 文件保存的路径  */
	private String finallPath;

	/**
	 * @param url 需要下载的URL
	 * @param savePath 文件保存的路径
	 * @param fileName 文件名
	 * @param suffixName 文件后缀
	 */
	public FileDownloaderUtil(String url,String savePath,String fileName,String suffixName) {
		this.url=url;
		String finallPath=savePath+fileName+suffixName;
		this.finallPath=finallPath;
	}
	public FileDownloaderUtil(String url,String savePath,String fileName) {
		this.url=url;
		String finallPath=savePath+fileName;
		this.finallPath=finallPath;
	}

	public void run( ) {
		System.out.println("[INFO] Download From : " + this.url);
		File file = new File(this.finallPath);
		if (file.exists())
			file.delete();
		try {
			// 使用file来写入本地数据
			file.createNewFile();
			FileOutputStream outStream = new FileOutputStream(this.finallPath);
			// 执行请求,获得响应
			HttpClient httpClient = new DefaultHttpClient();
			HttpGet httpGet = new HttpGet(url);	
			HttpResponse httpResponse = httpClient.execute(httpGet);
			
			
			System.out.println("[STATUS] Download : " + httpResponse.getStatusLine() + " [FROM] " + this.finallPath);
			HttpEntity httpEntity = httpResponse.getEntity();
			InputStream inStream = httpEntity.getContent();
			// 这个循环读取网络数据,写入本地文件
			while (true) {
				byte[] bytes = new byte[1024 * 1000];
				int k = inStream.read(bytes);
				if (k >= 0) {
					outStream.write(bytes, 0, k);
					outStream.flush();
				} else
					break;
			}
			inStream.close();
			outStream.close();
		} catch (IOException e) {
			System.out.println("[ERROR] Download IOException : " + e.toString() + " [文件保存到:] : " + this.finallPath);
			e.printStackTrace();
		}

	}

	
	public static void main(String[] args) {
		FileDownloaderUtil d = new FileDownloaderUtil("http://img.qichacha.com/Download/20170919155844468c2e1f.xls",
				"E:/findNewCompany/",TimeUtil.dateToStr(new Date())+"-",".xls"	);
		d.run();
	}
}
网友评论