从Java中给定范围内的URL逐字节读取

时间:2013-03-09 09:28:28

标签: java url bytearray httpurlconnection urlconnection

您好StackOverflow系列,

我的目标是获取给定范围内的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.");
        }

1 个答案:

答案 0 :(得分:0)

假设您要读取范围[startRange, finishRange]中的字节,一种解决方案是跳过起始字节,然后读取finishRange中的下一个InputStream

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
}