4 MINDS

4MINDS Gestão de Conhecimento

Split and save large file



Código em java para salvar um arquivo em várias partes.



File src = new File("/path/to/large/file.mp4");
InputStream in = new FileInputStream(src);

final int mb = 1048576; // 1MB
final int kb = 1024 * 4; // max buffer size
final int partSize = mb * 5; // max part size 5MB
byte[] buf = new byte[kb];
int len = 0;

int partCount = in.available() / partSize;

if(in.available() % partSize > 0)
    partCount++;                       

for(int i = 0; i < partCount; i++){

    ByteArrayOutputStream bStream = new ByteArrayOutputStream();
    int read = 0;

    while ((len = in.read(buf)) > 0) {
   
        read += len;
   
        bStream .write(buf, 0, len);

        if(read >= partSize){
            read = 0;
            break;
        }
    }                       

    File filePartSrc = new File("/path/to/file/parts/file_" + i + ".part");
    FileOutputStream fo = new FileOutputStream(filePartSrc);
    fo.write(bStream.toByteArray());
    fo.flush();
    fo.close();
    bStream.close();                                            
}

in.close();