File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes concatenating byte arrays Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "concatenating byte arrays" Watch "concatenating byte arrays" New topic

concatenating byte arrays

Alessandro Brawerman

Joined: Sep 22, 2003
Posts: 22
Hi all,
just a quick question.
I have 2 different byte arrays. They are of the same size.
How can I put then together in a third byte arrays? Like concatenating 2 string in a third one.
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
I don't think the API provides a method to do this, so you will have to do it by hand. It shouldn't be difficult to create a method to concatenate the two arrays. Think about it for a minute and let us know what you come up with.


p.s. Perhaps the arraycopy() method from the System class will be helpful in implementing this.
[ April 22, 2005: Message edited by: Layne Lund ]

Java API Documentation
The Java Tutorial
Alessandro Brawerman

Joined: Sep 22, 2003
Posts: 22
The arraycopy works.

This is the small test I ran to check.
byte[] t = "test".getBytes();
byte[] t1 = "test".getBytes();
byte[] t2 = new byte[8];
byte[] t3 = "testtest".getBytes();
if(Arrays.equals(t2,t3)) System.out.println("SAME");
else System.out.println("NO");
Stuart Gray
Ranch Hand

Joined: Apr 21, 2005
Posts: 410
You could also make the final thing more general by using the length property of each array:

byte[] t2 = new byte[t.length + t1.length];
System.arraycopy(t, 0, t2, 0, t.length);
System.arraycopy(t1, 0, t2, t.length, t2.length);
It is sorta covered in the JavaRanch Style Guide.
subject: concatenating byte arrays
jQuery in Action, 3rd edition