我尝试用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.   

    while ( (currentRead = inputStream.read(bytes,0,2048-1)) > 0)改成 while ( (currentRead = inputStream.read(bytes)) != -1)
      

  2.   

    To wuyg(平平) :
    你最好试一下,可以么? 我用的是78M的文件测试的,运行到30M的时候,中止程序(也就是中止了传输),紧接着继续传输最后就出现了异常了你能够试一下吗?
    我已经试过你的方法了,还是一样的异常:
    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)