suppose I have two String
s like
txt1="something 1";
txt2="something 2";
now wanted to create byte[] str= new byte[];
from those String
s
byte[] t1,t2;
t1=txt1.getBytes();
t2=txt2.getBytes();
byte[] strings = { t1,t2};
suppose I have two String
s like
txt1="something 1";
txt2="something 2";
now wanted to create byte[] str= new byte[];
from those String
s
byte[] t1,t2;
t1=txt1.getBytes();
t2=txt2.getBytes();
byte[] strings = { t1,t2};
Firstly, I would suggest not using getBytes()
without specifying the encoding first. (I generally prefer UTF-8, but it depends on what you want.)
Secondly, if you just want the bytes of one string followed by the bytes of another, the simplest approach is to use string concatenation:
byte[] data = (txt1 + txt2).getBytes(StandardCharsets.UTF_8);
Alternatively you can fetch each byte array separately, and then combine them by creating a new byte array which is large enough to hold both, and copying the data:
byte[] t1 = txt1.getBytes(StandardCharsets.UTF_8);
byte[] t2 = txt2.getBytes(StandardCharsets.UTF_8);
byte[] both = new byte[t1.length + t2.length];
System.arraycopy(t1, 0, both, 0, t1.length);
System.arraycopy(t2, 0, both, t1.length, t2.length);
I'd use the string concatenation version myself though :)
The easiest way would be:
byte[] strings = (t1+t2).getBytes();
Otherwise you'd have to manually allocate a large enough array and copy the individual bytes. I'm pretty sure there's no array-concatenation utility function in the standard API, though there might be one in Apache Commons or something...
Oh, and yes, usually yo want to specify the encoding when you use getBytes()
, rather than relying on the platform default encoding.
Because txt1.getBytes()
returns a byte[]
. You are trying to assign multiple byte[]
's in an array. Merge both the array and the assign into it.
byte[] combined = new byte[array1.length + array2.length];
You have to allocate the new byte array and copy the content of the two byte arrays into the new byte array:
byte[] t1 = txt1.getBytes();
byte[] t2 = txt2.getBytes();
byte[] result = new byte[t1.length + t2.length];
System.arraycopy(t1, 0, result, 0, t1.length);
System.arraycopy(t2, 0, result, t1.length, t2.length);
Simplest approach is to use string concatenation and convert into bytes array.
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
String txt1="something 1",txt2="something 2";
//Use '+' string concatenation and convert into byte array.
byte[] data = (txt1 + txt2).getBytes();
System.out.println(data);
}
}