2013-03-09 140 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