我尝试用HTTP实现文件的续传,代码狠简单,如下.
但当我用 大文件(如74 M)测试的时候,总有问题..
1、如果一次过传输完毕,则没问题。
2、如果传输过程中,断开连接,然后重新运行代码,则抛出异常."java.net.SocketException: Connection reset"
3、如果一次过传输完毕,然后再启动运行代码,又会抛出异常"Server returned HTTP response code: 416........"我的代码如下,欢迎大家讨论。。指出问题。。拜托。郁闷好久了。public static void main(String[] args)
{
   long breakPoint=0;
   try
   {
     String localPath = "G:\\Test\\Griends.mkv";
     File file = new File(localPath);
     if(file.exists())
        breakPoint=file.length(); //断点位置.问题在这里??     String targetURL = "http://localhost:8080/MobileServices/Friends.mkv";
     URL url = new URL(targetURL);
     HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();     //下面告诉服务器从breakPoint开始发送过来,而不需要重头(第0字节)发送.
     httpConnection.setRequestProperty("RANGE", "bytes=" + breakPoint+"-");
     RandomAccessFile localFile = new RandomAccessFile(file, "rw");
     localFile.seek(breakPoint); //跳到断点处再继续写文件...
     InputStream inputStream = httpConnection.getInputStream();
     byte[] bytes = new byte[2048];     int currentRead = 0;
     while ( (currentRead = inputStream.read(bytes,0,2048-1)) > 0)//异常在这里?奇怪噢.
     {
          localFile.write(bytes, 0, currentRead);
     }
   }
   catch (Exception e)
   {
      e.printStackTrace();
   }}

解决方案 »

  1.   

    To treeroot(旗鲁特) :
    不可以啊,你一次过传输完毕就没问题。但是当文件很大,然后传输过程中停了,然后再一次启动程序,直到下载结束之前,就会抛出异常了。。你可以试一下噢。。麻烦了。。
    则抛出异常."java.net.SocketException: Connection reset"
      

  2.   

    To treeroot(旗鲁特):
    不会吧???没出错??
    能否把你代码贴一下??我是在下载过程中,Eclipse下关闭程序的.这样下载就中断了。
    下次再启动程序,继续下载。首先检查已经有的文件的大小。
    但执行到最后总是抛出异常:
    java.net.SocketException: Connection reset
    at java.net.SocketInputStream.read(Unknown Source)
    at java.io.BufferedInputStream.fill(Unknown Source)
    at java.io.BufferedInputStream.read1(Unknown Source)
    at java.io.BufferedInputStream.read(Unknown Source)
    at sun.net.www.MeteredStream.read(Unknown Source)
    at java.io.FilterInputStream.read(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection$HttpInputStream.read(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection$HttpInputStream.read(Unknown Source)
    at Test.main(Test.java:38)你是用多大的文件测试的? 我是把一个78M的文件放到Tomcat服务器下测试的,在大概传输了30M左右,强行关闭程序,然后重新启动程序继续下载,到后来就抛出异常了。。
    可以的话,能否留下你的Email或者其他方式讨论一下? 我的是[email protected]