Java examples for java.lang:byte Array
Utility method used to ensure the capacity of byte array.
//package com.java2s; import java.util.Arrays; public class Main { public static void main(String[] argv) throws Exception { byte[] bytes = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 }; int capacity = 2; System.out.println(java.util.Arrays.toString(ensureCapacity(bytes, capacity)));/*from w w w . j a va2 s .c o m*/ } /** * Utility method used to ensure the capacity of byte array. * * @param bytes * @param size * @param factor * @return */ private static byte[] ensureCapacity(byte[] bytes, int capacity) { if (bytes.length < capacity) { int newsize = Math.max(1, bytes.length) << 1; bytes = Arrays.copyOf(bytes, newsize); } return bytes; } /** * Concatenate strings with the given separator char. * * @param strs * @param separator * @return */ public static String toString(String[] strs, char separator) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < strs.length; i++) { sb.append(strs[i]); if (i + 1 < strs.length) { sb.append(separator); } } return sb.toString(); } /** * Convert the bytes starting at the given index to a string of * the given length. * * @param bytes * @param index * @param strLeng * @return */ public static String toString(byte[] bytes, int index, int strLeng) { int typeBytes = Character.SIZE / Byte.SIZE; checkBounds(bytes, index, typeBytes * strLeng); StringBuilder sb = new StringBuilder(); for (int i = 0; i < strLeng; i++) { int c = 0; for (int j = 0; j < typeBytes; j++) { int b = bytes[index++]; b = (b < 0) ? b + 256 : b; int shiftBits = Byte.SIZE * j; c = (c << shiftBits) + b; } sb.append((char) c); } return sb.toString(); } /** * Utility method used to bounds check the byte array * and requested offset & length values. * * @param bytes * @param offset * @param length */ public static void checkBounds(byte[] bytes, int offset, int length) { if (length < 0) throw new IndexOutOfBoundsException("Index out of range: " + length); if (offset < 0) throw new IndexOutOfBoundsException("Index out of range: " + offset); if (offset > bytes.length - length) throw new IndexOutOfBoundsException("Index out of range: " + (offset + length)); } }