How to download a part of a file from URL in android?

前端 未结 2 1648
北海茫月
北海茫月 2020-12-18 09:02

I am trying to download a part of file given the download URL using setRequestProperty(\"Range\",\"bytes=\" + startbytes + \"-\" + endbytes); The following code snippet show

2条回答
  •  粉色の甜心
    2020-12-18 09:50

    Assuming you're using HTTP for the download, you'll want to use the HEAD http verb and RANGE http header.

    HEAD will give you the filesize (if available), and then RANGE lets you download a byte range.

    Once you have the filesize, divide it into roughly equal sized chunks and spawn download thread for each chunk. Once all are done, write the file chunks in the correct order.

    If you don't know how to use the RANGE header, here's another SO answer that explains how: https://stackoverflow.com/a/6323043/1355166

    [EDIT]

    To make file into chunks use this, and start the downloading process,

    private void getBytesFromFile(File file) throws IOException {
        FileInputStream is = new FileInputStream(file); //videorecorder stores video to file
    
        java.nio.channels.FileChannel fc = is.getChannel();
        java.nio.ByteBuffer bb = java.nio.ByteBuffer.allocate(10000);
    
        int chunkCount = 0;
    
        byte[] bytes;
    
        while(fc.read(bb) >= 0){
            bb.flip();
            //save the part of the file into a chunk
            bytes = bb.array();
            storeByteArrayToFile(bytes, mRecordingFile + "." + chunkCount);//mRecordingFile is the (String)path to file
            chunkCount++;
            bb.clear();
        }
    }
    
    private void storeByteArrayToFile(byte[] bytesToSave, String path) throws IOException {
        FileOutputStream fOut = new FileOutputStream(path);
        try {
            fOut.write(bytesToSave);
        }
        catch (Exception ex) {
            Log.e("ERROR", ex.getMessage());
        }
        finally {
            fOut.close();
        }
    }
    

提交回复
热议问题