/** * @author lautturi.com * Java example: combine two byte arrays in java */ import java.util.*; import java.io.UnsupportedEncodingException; public class Lautturi { public static void main(String[] args) { byte[] bytes1 = {104, 101, 108, 108, 111, 32}; byte[] bytes2 = {108, 97, 117, 116, 116, 117, 114, 105, 32, 106, 97, 118, 97, 33}; byte[] combined = new byte[bytes1.length + bytes2.length]; for (int i = 0; i < combined.length; ++i) { combined[i] = i < bytes1.length ? bytes1[i] : bytes2[i - bytes1.length]; } System.out.println(Arrays.toString(combined)); String str; try { str = new String(combined,"utf-8"); System.out.println(str); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
output:
[104, 101, 108, 108, 111, 32, 108, 97, 117, 116, 116, 117, 114, 105, 32, 106, 97, 118, 97, 33] hello lautturi java!