将给定数组拆分为给定大小的块,并在必要时向最后一个块添加填充。
/**来自 时 代 J a v a 公 众 号 - nowjava.com**/ import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Main{ public static void main(String[] argv) throws Exception{ byte[] byteArray = new byte[]{34,35,36,37,37,37,67,68,69}; int blocksize = 2; System.out.println(java.util.Arrays.toString(splitAndPad(byteArray,blocksize))); } /** * Splits the given array into blocks of given size and adds padding to the * last one, if necessary. * * @param byteArray * the array. * @param blocksize * the block size. * @return a list of blocks of given size. */ public static List<byte[]> splitAndPad(byte[] byteArray, int blocksize) { List<byte[]> blocks = new ArrayList<byte[]>(); int numBlocks = (int) Math.ceil(byteArray.length / (double) blocksize); for (int i = 0; i < numBlocks; i++) { byte[] block = new byte[blocksize]; Arrays.fill(block, (byte) 0x00); /* 来 自* 时代Java - N o w J a v a . c o m */ if (i + 1 == numBlocks) { // the last block int remainingBytes = byteArray.length - (i