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. Mysql字符集与校对规则

    字符集是一套字符和编码的集合,校对规则是用于比较字符集的一套规则. 所以字符集有两部分组成字符集合和对应的编码集合.比如说,现在有这几个字符:A B a b, 假设它们对应的编码分别是00, 01, ...

  2. (7)ASP.NET WEB服务器控件

    1. <body> <form id="form1" runat="server"> <div> <asp:Label ...

  3. CentOS6、CentOS7配置Base源和epel源

    1.用yum安装软件报错 Could not retrieve mirrorlist http://mirrorlist.centos.org/?release=6&arch=x86_64&a ...

  4. noip2015提高组day2解题报告

    1.跳石头 题目描述 一年一度的“跳石头”比赛又要开始了! 这项比赛将在一条笔直的河道中进行,河道中分布着一些巨大岩石.组委会已经选择好了两块岩石作为比赛起点和终点.在起点和终点之间,有 N 块岩石( ...

  5. UVA 111

    又被题意坑了... 输入的一串数字的含义是第i个数字是第a[i]个发生的.而不是编号为i的历史事件的实际发生顺序.所以第一步要做的是转换,将原始数据转换成编号为i的历史事件的实际发生顺序.然后按照实际 ...

  6. iOS WKWebView添加网页加载进度条(转)

    一.效果展示 WKWebProgressViewDemo.gif 二.主要步骤 1.添加UIProgressView属性 @property (nonatomic, strong) WKWebView ...

  7. 时序数据库TSDB简单了解

    由于项目需要,简单看来下时序数据库: 时序数据库是针对大量数据写入.主要用于记录时序数据的,使用于监控记录的场景:写多读少场景: 什么是时序数据.时序数据是基于时间的一系列的数据.在有时间的坐标中将这 ...

  8. DICOM医学图像显示算法改进与实现——LUT

    引言 随着Ul(超声成像).CT(计算机断层成像).MRI(核磁共振成像).CR(计算机X线成像).电子内窥镜.盯(正电子发射断层成像)和MI(分子影像)等医学影像设备不断涌现,利用计算机对医学影像设 ...

  9. pandas入门指南

    上一篇讲了numpy,除此之外,还有一个工具我们一定会使用,那就是pandas.如果说numpy中数据存储形式是列表的话,那么pandas中数据的存储形式更像是字典.为什么这么说呢?因为pandas中 ...

  10. 【转载】分布式RPC框架性能大比拼

    dubbo.motan.rpcx.gRPC.thrift的性能比较 Dubbo 是阿里巴巴公司开源的一个Java高性能优秀的服务框架,使得应用可通过高性能的 RPC 实现服务的输出和输入功能,可以和 ...