• 用Java实现断点续传的基本思路和代码


    用Java实现断点续传的基本思路和代码

    URL url = new URL(http://www.oschina.net/no-exist.zip);

    HttpURLConnection httpConnection = (HttpURLConnection)url.openConnection();

    //设置User-Agent
    httpConnection.setRequestProperty("User-Agent","NetFox");
    //设置断点续传的开始位置
    httpConnection.setRequestProperty("RANGE","bytes=2000070");
    //获得输入流
    InputStream input = httpConnection.getInputStream();
    /**
    从输入流中取出的字节流就是no-exist.zip文件从2000070开始的字节流。
    大家看,其实断点续传用Java实现起来还是很简单的吧。
    接下来要做的事就是怎么保存获得的流到文件中去了。
    (2)保存文件采用的方法
    我采用的是IO包中的RandAccessFile类。操作相当简单,假设从2000070处开始保存文件,代码如下:
     
    */
     
    RandomAccessFile oSavedFile = new RandomAccessFile("down.zip","rw");
     
    long nPos = 2000070;
     
    //定位文件指针到nPos位置
     
    oSavedFile.seek(nPos);
     
    byte[] b = new byte[1024];
     
    int nRead;
     
    //从输入流中读入字节流,然后写到文件中
     
    while((nRead=input.read(b,0,1024)) > 0)
     
    {
     
    oSavedFile.write(b,0,nRead);
     
    }

    转自:http://www.oschina.net/code/snippet_54100_623

  • 相关阅读:
    JAVA规范
    JMS开发指南
    JMS异步消息机制
    大型系统中使用JMS优化技巧–Sun OpenMQ
    02.MyBatis配置文件详解
    elasticsearch.yml配置文件
    04.ActiveMQ与Spring JMS整合
    01.MyBatis入门
    03.JMS深入
    02.JMS基础
  • 原文地址:https://www.cnblogs.com/apache-x/p/5335951.html
Copyright © 2020-2023  润新知