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. Security arrangements for extended USB protocol stack of a USB host system

    Security arrangements for a universal serial bus (USB) protocol stack of a USB host system are provi ...

  2. 解决 Mac OS X Retina 屏幕显示环境下 jEdit 字体模糊的方法

    Mac OS X Retina 屏幕显示环境下,字体非常清晰.但是 jEdit 仍然很模糊,虽然 jEdit 用的是 Java,但这并不是理由.因为诸如 NetBeans 以及 IntelliJ ID ...

  3. Cookie 和 Session 有什么区别呢?

    Cookie 和 Session 有什么区别呢?大部分的面试者应该都可以说上一两句,比如:什么是 Cookie?什么是 Session?两者的区别等 但如果再往深入探讨的话,就慢慢有一些朋友不太了解了 ...

  4. Chrome查看同步状态

    最近Hosts不太稳定,翻出去之后安装了一些插件,那么会面临一些问题,比如插件是否已经同步成功,其它PC能否获取等等. 下面是一些查询同步状态的入口: https://www.google.com/s ...

  5. MySQL 5.6.20-4 and Oracle Linux DTrace

    https://blogs.oracle.com/wim/entry/mysql_5_6_20_4?utm_source=tuicool&utm_medium=referral By WimC ...

  6. android 图片的平移,缩放和旋转

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools= ...

  7. svm、logistic regression对比

    相同点:都是线性分类算法 不同点: 1.损失函数不同 LR:基于“给定x和参数,y服从二项分布”的假设,由极大似然估计推导 SVM: hinge loss + L2 regularization的标准 ...

  8. Python机器学习--手写体识别(KNN+MLP)

    MLP实现 调整参数比较性能结果 # -*- coding: utf-8 -*- """ Created on Wed Aug 30 21:14:38 2017 @aut ...

  9. 怎样提高hbase的入库性能

    hbase写数据首先先写入memstore.当memstore满64MB以后,会flush到disk上而成为storefile.当storefile数量超过3时,会启动compaction过程将它们合 ...

  10. Lambda 表达式的演示样例-来源(MSDN)

    本文演示怎样在你的程序中使用 lambda 表达式. 有关 lambda 表达式的概述.请參阅 C++ 中的 Lambda 表达式. 有关 lambda 表达式结构的具体信息,请參阅 Lambda 表 ...