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");
    	}
    }


  • 相关阅读:
    水平居中
    flex布局
    get新技能:上传了 flv 或 MP4 文件到服务器,可访问总是出现 “无法找到该页”的 404 错误
    小程序3.8
    小程序3.7
    Vue 中select option默认选中的处理方法
    HTML5 data属性
    静态html返回
    node中可读流、可写流
    node.js fs、http使用
  • 原文地址:https://www.cnblogs.com/yht520/p/3589652.html
Copyright © 2011-2022 走看看