• Post Reply Bookmark Topic Watch Topic
  • New Topic

how to split byte[] to smaller chunks  RSS feed

 
Daniel Bauer
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi i have a big file.i have loaded this file to byte[].

now i want to split this byte[] to smaller byte[] chunks of byte[500].

how to do this ?
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24215
37
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There's no way except for the direct way -- in a "for" loop, allocate 500-byte arrays, and use System.arraycopy() to copy data from the big array into them.
 
Daniel Bauer
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public static void splitBytes(byte[] fileBytes) throws Exception {


int offset = 0;
int fileCounter = 0;

while (offset < fileBytes.length) {
byte[] outputBytes;

if(fileBytes.length - offset < 500 ) {
outputBytes = new byte[fileBytes.length - offset];
System.arraycopy(fileBytes, offset, outputBytes, 0, fileBytes.length - offset);
saveFile(outputBytes , fileCounter++);
break;
}

outputBytes = new byte[500];
System.arraycopy(fileBytes, offset, outputBytes, 0, 500);
offset +=500 ;
saveFile(outputBytes , fileCounter++);
Thread.sleep(3000);

}

}
 
Daniel Bauer
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
or with a recursion

public static void splitBytes(byte[] fileBytes, int offset , int fileCounter) throws Exception {

byte[] outputBytes;

if(fileBytes.length - offset < 500 ) {
outputBytes = new byte[fileBytes.length - offset];
System.arraycopy(fileBytes, offset, outputBytes, 0, fileBytes.length - offset);
saveFile(outputBytes , fileCounter++);
return;
}

outputBytes = new byte[500];
System.arraycopy(fileBytes, offset, outputBytes, 0, 500);
saveFile(outputBytes , fileCounter++);
Thread.sleep(3000);
splitBytes(fileBytes,offset+500, fileCounter++);


}
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!