zoukankan      html  css  js  c++  java
  • Java断点续传(简单实现)

    public class BreakPointDownLoad {
    	private int bufferSize = 32;
    
    	public void URLLoad(String sourceUrl, String fileName) {
    		InputStream input = null;
    		RandomAccessFile access = null;
    		try {
    			// 获取资源
    			URL url = new URL(sourceUrl);
    			input = url.openStream();
    			// 初始化存储文件
    			File file = new File(fileName);
    			if (!file.exists()) {
    				file.createNewFile();
    			}
    			// 资源长度
    			long sourceSize = url.openConnection().getContentLength();
    			// 存储文件长度
    			long fileSize = file.length();
    			long pointSize = 0;
    			// 判断是否已下载完成
    			if (sourceSize > fileSize) {
    				// 断点下载
    				pointSize = fileSize;
    			} else {
    				// 重新下载
    				file.delete();
    				file.createNewFile();
    			}
    			access = new RandomAccessFile(file, "rw");
    			// 资源,文件定位
    			input.skip(pointSize);
    			access.seek(pointSize);
    			byte[] buffer = new byte[bufferSize];
    			int count = 0;
    			System.out.println("正在下载...");
    			while ((count = input.read(buffer)) != -1) {
    				access.write(buffer, 0, count);
    			}
    		} catch (MalformedURLException e) {
    			e.printStackTrace();
    		} catch (IOException e) {
    			e.printStackTrace();
    		} finally {
    			try {
    				input.close();
    				access.close();
    			} catch (IOException e) {
    				e.printStackTrace();
    			}
    		}
    		System.out.println("下载完成");
    	}
    
    	public static void main(String[] args) {
    		BreakPointDownLoad load = new BreakPointDownLoad();
    		load.URLLoad("http://www.baidu.com/", "D:/juhua.html");
    	}
    }


  • 相关阅读:
    CSS3实现平行四边形
    [Python]图的遍历-DFS
    [Python]图的遍历-BFS
    [Python]图的遍历-拓扑排序
    [Python]哈夫曼编码
    [Python]贪心算法-Prim-和-Kruskal实现-最小生成树
    [Python]贪心算法-Dijkstra-实现
    [python3]稳定匹配算法实现和优化
    从csv文件构建Tensorflow的数据集
    Tensorflow 基础API
  • 原文地址:https://www.cnblogs.com/yht520/p/3589652.html
Copyright © 2011-2022 走看看