Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a String array to a Byte array? (java)

I have a one dimensional String array that I want to convert into a one dimensional byte array. How do I do this? Does this require ByteBuffer? How can I do this? (The strings can be any length, just want to know how to go about doing such an act. And after you convert it into a byte array how could I convert it back into a String array?

-Dan

like image 830
Code Doggo Avatar asked Feb 03 '13 05:02

Code Doggo


1 Answers

You don't say what you want to do with the bytes (aside from convert them back to a String[] afterward), but assuming you can just treat them as an opaque bag of data (so you can save them to a file or send them over the network or whatnot, but you don't need to examine or modify them in any way), I think your best bet is to use serialization. To serialize your string-array, you would write something like:

final String[] stringArray = { "foo", "bar", "baz" };

final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
final ObjectOutputStream objectOutputStream =
    new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(stringArray);
objectOutputStream.flush();
objectOutputStream.close();

final byte[] byteArray = byteArrayOutputStream.toByteArray();

and to recover it afterward, you'd write the reverse:

final ByteArrayInputStream byteArrayInputStream =
    new ByteArrayInputStream(byteArray);
final ObjectInputStream objectInputStream =
    new ObjectInputStream(byteArrayInputStream);

final String[] stringArray2 = (String[]) objectInputStream.readObject();

objectInputStream.close();
like image 187
ruakh Avatar answered Sep 16 '22 12:09

ruakh