stackoverflow代码
public static boolean isMatch(byte[] pattern, byte[] input, int pos) { for(int i=0; i< pattern.length; i++) { if(pattern[i] != input[pos+i]) { return false; } } return true; } public static List<byte[]> split(byte[] pattern, byte[] input) { List<byte[]> l = new LinkedList<byte[]>(); int blockStart = 0; for(int i=0; i<input.length; i++) { if(isMatch(pattern,input,i)) { l.add(Arrays.copyOfRange(input, blockStart, i)); blockStart = i+pattern.length; i = blockStart; } } l.add(Arrays.copyOfRange(input, blockStart, input.length )); return l; }
引申出来的泛型代码:
public static <T> boolean isMatch0(T[] pattern, T[] input, int position) { for(int i=0; i< pattern.length; i++) { if(pattern[i] != input[position+i]) { return false; } } return true; } public static <T> List<T[]> split(T[] pattern, T[] input) { List<T[]> l = new LinkedList<T[]>(); int blockStart = 0; for(int i=0; i<input.length; i++) { if(isMatch0(pattern,input,i)) { l.add(Arrays.copyOfRange(input, blockStart, i)); blockStart = i+pattern.length; i = blockStart; } } l.add(Arrays.copyOfRange(input, blockStart, input.length )); return l; }
public <T> List<T[]> split(T[] original, int size) { List<T[]> result = new ArrayList<T[]>(); if (original == null) return result; int curPos = 0; while (curPos < original.length) { int remaining = original.length - curPos+1; if (remaining <= size) { result.add(Arrays.copyOfRange(original,curPos,original.length)); } else { result.add(Arrays.copyOfRange(original,curPos,curPos+size)); } curPos += size; } return result; }
byte[] data = { 2, 3, 5, 7, 8, 9, 11, 12, 13 }; int blockSize = 3; int blockCount = (data.length + blockSize - 1) / blockSize; byte[] range = null; for (int i = 1; i < blockCount; i++) { int idx = (i - 1) * blockSize; range = Arrays.copyOfRange(data, idx, idx + blockSize); System.out.println("Chunk " + i + ": " Arrays.toString(range)); } // Last chunk int end = -1; if (data.length % blockSize == 0) { end = data.length; } else { end = data.length % blockSize + blockSize * (blockCount - 1); } range = Arrays.copyOfRange(data, (blockCount - 1) * blockSize, end); System.out.println("Chunk " + blockCount + ": " Arrays.toString(range));
https://gist.github.com/lesleh/7724554
以上代码不能分割byte数组,分割byte数组如下
byte[] data = { 2, 3, 5, 7, 8, 9, 11, 12, 13 }; int blockSize = 3; int blockCount = (data.length + blockSize - 1) / blockSize; byte[] range = null; for (int i = 1; i < blockCount; i++) { int idx = (i - 1) * blockSize; range = Arrays.copyOfRange(data, idx, idx + blockSize); System.out.println("Chunk " + i + ": " Arrays.toString(range)); } // Last chunk int end = -1; if (data.length % blockSize == 0) { end = data.length; } else { end = data.length % blockSize + blockSize * (blockCount - 1); } range = Arrays.copyOfRange(data, (blockCount - 1) * blockSize, end); System.out.println("Chunk " + blockCount + ": " Arrays.toString(range));