1. [代码]Download.java   
package core.spider;
 
import java.io.*;
import java.net.*;
import java.util.*;
 
// This class downloads a file from a URL.
class Download extends Observable implements Runnable {
     
    // Max size of download buffer.
    private static final int MAX_BUFFER_SIZE = 1024;
     
    // These are the status names.
    public static final String STATUSES[] = {"Downloading",
    "Paused", "Complete", "Cancelled", "Error"};
     
    // These are the status codes.
    public static final int DOWNLOADING = 0;
    public static final int PAUSED = 1;
    public static final int COMPLETE = 2;
    public static final int CANCELLED = 3;
    public static final int ERROR = 4;
     
    private URL url; // download URL
    private int size; // size of download in bytes
    private int downloaded; // number of bytes downloaded
    private int status; // current status of download
     
    // Constructor for Download.
    public Download(URL url) {
        this.url = url;
        size = -1;
        downloaded = 0;
        status = DOWNLOADING;
         
        // Begin the download.
        download();
    }
     
    // Get this download's URL.
    public String getUrl() {
        return url.toString();
    }
     
    // Get this download's size.
    public int getSize() {
        return size;
    }
     
    // Get this download's progress.
    public float getProgress() {
        return ((float) downloaded / size) * 100;
    }
     
    // Get this download's status.
    public int getStatus() {
        return status;
    }
     
    // Pause this download.
    public void pause() {
        status = PAUSED;
        stateChanged();
    }
     
    // Resume this download.
    public void resume() {
        status = DOWNLOADING;
        stateChanged();
        download();
    }
     
    // Cancel this download.
    public void cancel() {
        status = CANCELLED;
        stateChanged();
    }
     
    // Mark this download as having an error.
    private void error() {
        status = ERROR;
        stateChanged();
    }
     
    // Start or resume downloading.
    private void download() {
        Thread thread = new Thread(this);
        thread.start();
    }
     
    // Get file name portion of URL.
    private String getFileName(URL url) {
        String fileName = url.getFile();
        return fileName.substring(fileName.lastIndexOf('/') + 1);
    }
     
    // Download file.
    public void run() {
        RandomAccessFile file = null;
        InputStream stream = null;
         
        try {
            // Open connection to URL.
            HttpURLConnection connection =
                    (HttpURLConnection) url.openConnection();
             
            // Specify what portion of file to download.
            connection.setRequestProperty("Range",
                    "bytes=" + downloaded + "-");
             
            // Connect to server.
            connection.connect();
             
            // Make sure response code is in the 200 range.
            if (connection.getResponseCode() / 100 != 2) {
                error();
            }
             
            // Check for valid content length.
            int contentLength = connection.getContentLength();
            if (contentLength < 1) {
                error();
            }
             
            // Set the size for this download if it hasn't been already set.
            if (size == -1) {flash插件
                size = contentLength;
                stateChanged();
            }
             
            // Open file and seek to the end of it.
            file = new RandomAccessFile(getFileName(url), "rw");
            file.seek(downloaded);
             
            stream = connection.getInputStream();
            while (status == DOWNLOADING) {
            // Size buffer according to how much of the file is left to download.
                byte buffer[];http://www.huiyi8.com/flashchajian/image/
                if (size - downloaded > MAX_BUFFER_SIZE) {
                    buffer = new byte[MAX_BUFFER_SIZE];
                } else {
                    buffer = new byte[size - downloaded];
                }
                 
                // Read from server into buffer.
                int read = stream.read(buffer);
                if (read == -1)
                    break;
                 
                // Write buffer to file.
                file.write(buffer, 0, read);
                downloaded += read;
                stateChanged();
            }
             
      // Change status to complete if this point was reached because downloading has finished.
            if (status == DOWNLOADING) {
                status = COMPLETE;
                stateChanged();
            }
        } catch (Exception e) {
            error();
        } finally {
            // Close file.
            if (file != null) {
                try {
                    file.close();
                } catch (Exception e) {}
            }
             
            // Close connection to server.
            if (stream != null) {
                try {
                    stream.close();
                } catch (Exception e) {}
            }
        }
    }
     
    // Notify observers that this download's status has changed.
    private void stateChanged() {
        setChanged();
        notifyObservers();
    }
 
    public static void main(String args[]){
        try {
        Download d = new Download(new URL("http://www.oschina.net/img/logo.gif"));
        d.run();
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    }
}

Java 通过 HTTP 下载文件的更多相关文章

  1. java 的在线下载文件 .pdf

    java  的在线下载文件  .pdf 1.下载资源的本地位置 2.设置响应头 3.下载代码 1 PeriodicalResource periodicalResource = periodicalR ...

  2. 《手把手教你》系列技巧篇(五十六)-java+ selenium自动化测试-下载文件-上篇(详细教程)

    1.简介 前边几篇文章讲解完如何上传文件,既然有上传,那么就可能会有下载文件.因此宏哥就接着讲解和分享一下:自动化测试下载文件.可能有的小伙伴或者童鞋们会觉得这不是很简单吗,还用你介绍和讲解啊,不说就 ...

  3. 《手把手教你》系列技巧篇(五十七)-java+ selenium自动化测试-下载文件-下篇(详细教程)

    1.简介 前边几篇文章讲解完如何上传文件,既然有上传,那么就可能会有下载文件.因此宏哥就接着讲解和分享一下:自动化测试下载文件.可能有的小伙伴或者童鞋们会觉得这不是很简单吗,还用你介绍和讲解啊,不说就 ...

  4. 多线程爬虫Java调用wget下载文件,独立线程读取输出缓冲区

    写了个抓取appstore的,要抓取大量的app,本来是用httpclient,但是效果不理想,于是直接调用wget下载,但是由于标准输出.错误输出的原因会导致卡住,另外wget也会莫名的卡住. 所以 ...

  5. Java Web之下载文件

    下载的文件,不能随便的被访问,放在外面的文件夹肯定不行,url一敲就能访问了,所以我们要放在WEB-INF文件夹里面,WEB-INF文件夹只有Servlet才能访问,我们新建一个文件夹,叫downlo ...

  6. Java 从服务器下载文件到本地(页面、后台、配置都有)

    先来看实现效果: 有一个链接如下: 点击链接下载文件:  第一种方法:Servlet实现 一.HTML页面部分: 1.HTML页面中的一个链接 <a id="downloadTempl ...

  7. java 从网上下载文件的几种方式

    package com.github.pandafang.tool; import java.io.BufferedOutputStream; import java.io.File; import ...

  8. Java多线程断点下载文件

    Java实现断点续传+多线程下载 如下代码所示,每一步都有注解 思路: 通过URL连接到服务器上要下载的文件,得到文件的大小: 算出每条线程下载的开始位置和结束位置,例如,有两条线程下载100Byte ...

  9. java多线程批量下载文件

    多线程下载文件 平时开发中有时会用到文件下载,为了提高文件的下载速率,采用多线程下载能够达到事半功倍的效果: package test; /** * 文件下载类 * @author luweichen ...

  10. java+web+批量下载文件

    JavaWeb 文件下载功能 文件下载的实质就是文件拷贝,将文件从服务器端拷贝到浏览器端,所以文件下载需要IO技术将服务器端的文件读取到,然后写到response缓冲区中,然后再下载到个人客户端. 1 ...

随机推荐

  1. GridView选中,编辑,取消,删除代码

    原文发布时间为:2008-08-03 -- 来源于本人的百度文章 [由搬家工具导入] 2.GridView选中,编辑,取消,删除: 效果图: 后台代码:你可以使用sqlhelper,本文没用。代码如下 ...

  2. Set 技巧之一

    我们知道set中 用set<int,int>S; S.lower_bound(x): 查找Set中 第一个>=x的数,返回结果是指针. S.upper_bound(x):查找Set中 ...

  3. Docker资源限制实现——cgroup

    摘要 随着Docker技术被越来越多的个人.企业所接受,其用途也越来越广泛.Docker资源管理包含对CPU.内存.IO等资源的限制,但大部分Docker使用者在使用资源管理接口时往往还比较模糊. 本 ...

  4. Linux常用C函数-接口处理篇(网络通信函数)

    接口处理篇accept,bind,connect,endprotoent,endservent,getsockopt,htonl,htons,inet_addr,inet_aton,inet_ntoa ...

  5. BUPT复试专题—数据库检索(2014软院)

    题目描述 在数据库的操作过程中,我们进场会遇到检索操作.这个题目的任务是完成一些特定格式的检索,并输出符合条件的数据库中的所有结果. 我们现在有一个数据库,维护了学生的姓名(Name),性别(Sex) ...

  6. 国内90%以上的 iOS 开发者,对 APNs 的认识都是错的

    转:http://toutiao.com/a6276578687162040578/?tt_from=weixin&utm_campaign=client_share&app=news ...

  7. cocos2d-x wp8 中文显示问题

    cocos2d-x项目在wp8下中文显示不了.有两个原因: 1. 本身字符串的utf8编码, 有问题. 2. 显示中文所须要的字体,缺失. 要解决第二个问题非常easy,在fonts下加入一个中文字体 ...

  8. Solidworks打印工程图超出范围了怎么办

    打印预览,边框部分无法显示   页面设置,比例改为90%,试一下   正常了,如果你还是无法正常显示,就再改小比例

  9. docker on UP Board

    前言 原创文章,转载引用务必注明链接.水平有限,如有疏漏,欢迎指正. 本文使用Markdown写成,为获得更好的阅读体验和正常的图片.链接,请访问我的博客: http://www.cnblogs.co ...

  10. JMeter 系列之—-02 创建数据库测试计划

    Jmeter创建数据库测试计划,包括如下步骤: 1. 添加数据库jar包 使用不同的数据库,要引入不同的jar包.主要有两种方式: 方式1:直接将jar包复制到jmeter的lib目录 方式2:通过测 ...