0

嗨 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.");
        }
4

1 回答 1

0

假设您要读取 range 中的字节,一种解决方案是跳过起始字节,[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
}
于 2013-03-09T09:47:20.990 回答