2013-03-09 143 views
0

嗨StackOverflow的家人给定范围的URL,读取字节从Java中

我的目标是获得一个URL文件的内容,在给定的范围内。为了做到这一点,我有两个字节,一个是开始字节,另一个是结束字节。

但是,我不知道该怎么做。我实际上是通过使用一个字节数组逐字节读取的。

我在代码中添加了解释,谢谢。

这里是我的代码:

 // Scenario - 1 
     if(args.length == 3){ // 3 OLACAK 
      con.setRequestMethod("GET"); 

      fromURL = new BufferedInputStream(con.getInputStream(), bufSize); 
      toFile = new BufferedOutputStream(new FileOutputStream(outputFile), bufSize); 

      if(con.getResponseCode() == HttpURLConnection.HTTP_OK){ 
       // READING BYTE BY BYTE HERE 
       int read = -1; 
       byte[] buf = new byte[bufSize]; 
       while ((read = fromURL.read(buf, 0, bufSize)) >= 0) { 
        toFile.write(buf, 0, read); 
       } 
       toFile.close(); 
       System.out.println("ok"); 
      } 
     // Scenario - 2 
     }else if(args.length == 0){ 
      con.setRequestMethod("HEAD"); 

      if(con.getResponseCode() == HttpURLConnection.HTTP_OK){ 
       byte startRange = 0; //Integer.parseInt(args[3]); 
       byte finishRange = 25;//Integer.parseInt(args[4]); 


       System.out.println(con.getContentLength()); 
       if(startRange < 0 || finishRange > ((byte)con.getContentLength())){ 
        System.out.println("Range is not OK."); 
       }else{      

        int read = -1; 
        byte[] buf = new byte[finishRange]; 

        // HOW TO INCLUDE START AND END BYTES TO THIS PART OF CODE?????? 
        ////////////////////////////////////////////////////////////// 
        while ((read = fromURL.read(buf, 0, finishRange)) >= startRange) { 
         //toFile.write(buf, 0, read); 
        } 
        toFile.close(); 

        System.out.println("AAA"); 
       } 
      } 
     }else{ 
      System.out.println("Wrong argument count."); 
     } 

回答

0

假设你想读的范围[startRange, finishRange]字节,一个解决办法是跳过起始字节,然后在InputStream读取下一个finishRange

long skipped = fromURL.skip(startRange); 
if(skipped == startRange) { 
    // OK There was enough bytes to be skipped 
    if((read = fromURL.read(buf, 0, finishRange)) > -1) { 
     //toFile.write(buf, 0, read); 
    } 
} else { 
    // TODO Handle error when there was not enough bytes to be skipped 
} 
+0

感谢您的回答,但我总是得到跳过的变量为0,无论我写入startRange。这怎么会发生? – 2013-03-09 12:44:52

+0

这是发生在场景1还是场景2? – aymeric 2013-03-09 17:34:07