Search code examples
androidfilehttpjoinsegment

Android: Joining multipart files together to make a single file


I'm working on an android application which can download files in several parallel segments. I have them separately, and now I want to join them all together.

To be more clear, I will show you it by an simple example. Lets say I downloaded 100kb file in 4 segments. 1st segment is from 0kb to 25kb, 2nd is from 25kb to 50kb, 3rd is from 50kb - 75kb and the last segment is from 75kb-100kb. Filetype can be mp3, avi and etc.

Now I need to join them so that those segments (file parts) become a single file. I hope you could help me with this. Thanks for your time!

Edit: for an example its more like segmented avi(xxx.avi.001, xxx.avi.002, xxx.avi.003) files that we sometimes download into our PC and join the files using HJSplit into one file.


Solution

  • Try in this way, read from separate file one by one and write into one file. below simple code for your understanding. try this, i hope it will work for you. you can improve this code.

        InputStream in1 = new FileInputStream("sourceLocation1");
        InputStream in2 = new FileInputStream("sourceLocation2");
        InputStream in3 = new FileInputStream("sourceLocation3");
        InputStream in4 = new FileInputStream("sourceLocation4");
    
        OutputStream out = new FileOutputStream("targetLocation");
    
        // Copy the bits from instream to outstream
        byte[] buf = new byte[1024];
        int len;
    
        while ((len = in1.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
    
        while ((len = in2.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
    
        while ((len = in3.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
    
        while ((len = in4.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
    
        in1.close();
        in2.close();
        in3.close();
        in4.close();
        out.close();