- package org.sce.web;
- import java.io.BufferedInputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.net.HttpURLConnection;
- import java.net.URL;
- public class Download implements Runnable {
- private static final int BUFFER_SIZE = 4096;
- private String destUrl;
- private String fileName;
- public Download(String destUrl, String fileName) {
- this.destUrl = destUrl;
- int i = destUrl.lastIndexOf("/");
- this.fileName = fileName + destUrl.substring(i + 1);
- }
- public void run() {
- try {
- saveToFile(destUrl, fileName);
- System.out.println("download done,saved as: " + fileName);
- } catch (IOException e) {
- System.out.println("downloading error: " + e.getMessage());
- }
- }
- public void saveToFile(String destUrl, String fileName) throws IOException {
- FileOutputStream fos = null;
- BufferedInputStream bis = null;
- HttpURLConnection httpconn = null;
- URL url = null;
- byte[] buf = new byte[BUFFER_SIZE];
- int size = 0;
- // create connection
- url = new URL(destUrl);
- httpconn = (HttpURLConnection) url.openConnection();
- // connect the resource
- httpconn.connect();
- // get BufferedInputStream
- bis = new BufferedInputStream(httpconn.getInputStream());
- // create FileOutputStream for file
- fos = new FileOutputStream(fileName);
- System.out.println("connecting " + destUrl + "...");
- //save file
- while ((size = bis.read(buf)) != -1)
- fos.write(buf, 0, size);
- fos.close();
- bis.close();
- httpconn.disconnect();
- }
- public static void main(String[] args) {
- String url="http://www.cxybl.com/templets/default/p_w_picpaths/logo1.gif";
- String path="D:/download/";
- Download d=new Download(url,path);
- Thread th = new Thread(d);
- th.start();
- }
- }
转载于:https://blog.51cto.com/1956825/658615