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


  • 相关阅读:
    appium自动化测试搭建
    How to install Qt Creator on Ubuntu 18.04
    Luci
    OpenWrt 根文件系统启动过程分析
    shell 杂烩
    OpenWrt Luci 调试日志输出的一种方法
    jQuery实现购物车计算价格的方法
    js实现购物车添加,减少数量
    golang-键盘录入数据
    JAVA存储机制(栈、堆、方法区详解)
  • 原文地址:https://www.cnblogs.com/yht520/p/3589652.html
Copyright © 2011-2022 走看看