13

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

Code Doggo
  • 2,146
  • 6
  • 33
  • 58
  • You can iterate for each string and keep appending to the final byte array.String example = "This is an example"; //Convert String to byte[] using .getBytes() function byte[] bytes = example.getBytes(); //Convert byte[] to String using new String(byte[]) String s = new String(bytes); – sumeet kumar Feb 03 '13 at 05:41
  • Have you seen this question? http://stackoverflow.com/questions/1536054/how-to-convert-byte-array-to-string-and-vice-versa – Alina B. Feb 03 '13 at 05:45
  • Ali B - I think the question you linked answers a slightly different question - especially when you see the accepted answer, which rightly points out that "if you really want to store binary data in a String type, you should use Base64 encoding. – Floris Feb 03 '13 at 05:49
  • There is nounique representation of a string as bytes. What character encoding do you want to use? – Raedwald Oct 31 '14 at 21:10

7 Answers7

14

Array to Array you should convert manually with parsing into both sides, but if you have just a String you can String.getBytes() and new String(byte[] data); like this

public static void main(String[] args) {
    String[] strings = new String[]{"first", "second"};
    System.out.println(Arrays.toString(strings));
    byte[][] byteStrings = convertToBytes(strings);
    strings = convertToStrings(byteStrings);
    System.out.println(Arrays.toString(strings));

}

private static String[] convertToStrings(byte[][] byteStrings) {
    String[] data = new String[byteStrings.length];
    for (int i = 0; i < byteStrings.length; i++) {
        data[i] = new String(byteStrings[i], Charset.defaultCharset());

    }
    return data;
}


private static byte[][] convertToBytes(String[] strings) {
    byte[][] data = new byte[strings.length][];
    for (int i = 0; i < strings.length; i++) {
        String string = strings[i];
        data[i] = string.getBytes(Charset.defaultCharset()); // you can chose charset
    }
    return data;
}

for one byte[] from string[] you have to:

  • to byteArray concat byte arrays from each string using some delimeter
  • from bytearray split by te same delimiter and create String as I described above.
Sergii Zagriichuk
  • 5,389
  • 5
  • 28
  • 45
4

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();
ruakh
  • 175,680
  • 26
  • 273
  • 307
  • I like this because it separates the String array, so if you are writing to a file and later reading it, you can separate the objects without having to worry about a String delimiter. But my question is will the behavior of ObjectInputStream and ObjectOutputStream stay the same through different versions of Java, or will a file saved with an old JRE become unstable at some point? – EngineerWithJava54321 Feb 13 '16 at 21:08
1

You can check this

package javaapplication2;

import java.util.Arrays;


/**
 *
 * @author Ali
 */
public class JavaApplication2 {


 public static byte[] to_byte(String[] strs) {
        byte[] bytes=new byte[strs.length];
        for (int i=0; i<strs.length; i++) {
            bytes[i]=Byte.parseByte(strs[i]);
        }
        return bytes;
    }


    public static void main(String[] args) {
        String[] input = {"1","2","3"};       //original data
        byte[] byteArray = to_byte(input);//data to byte array
        String[] recovered=Arrays.toString( byteArray).split(",");// recovered data 

    }    
}
Ali Siam
  • 57
  • 6
1

First declare the string like I declared here str="Suresh"
Second use getBytes() to convert it in bytes
getBytes returns the array of byte.

String str="Suresh";
byte[] s=str.getBytes();
Gary
  • 13,303
  • 18
  • 49
  • 71
0

String.getBytes()? is what you're looking for.

Aniket Inge
  • 25,375
  • 5
  • 50
  • 78
  • Do I have to do that on every string? But doesnt that just convert a single string into a byte array? I have a bunch of strings that I wanna keep together into an array of bytes... I guess I could use it, just wanted to see if there was a way to do with out doing that. Thanks – Code Doggo Feb 03 '13 at 05:44
  • you can first concatenate them into one big string, and then get bytes on them? @DanielH – Aniket Inge Feb 03 '13 at 05:45
  • 1
    @DanielH - there is no way to go directly from `String[]` to `byte[]` - you'll have to iterate through your `String[]` and convert each one, then place it into your `byte[]` – Brian Roach Feb 03 '13 at 05:46
  • Thank you. I got it all working from all the information ive gathered from these responses. Thanks again – Code Doggo Feb 03 '13 at 07:36
  • Err, String doesn't have that method. At least not in my Java. – Thufir Aug 31 '13 at 07:03
0

I would treat this as a serialization problem and just implemented it as follows(complete and working Java code):

import java.nio.ByteBuffer;
import java.util.ArrayList;

public class Serialization {
    public static byte[] serialize(String[] strs) {
        ArrayList<Byte> byteList = new ArrayList<Byte>();
        for (String str: strs) {
            int len = str.getBytes().length;
            ByteBuffer bb = ByteBuffer.allocate(4);
            bb.putInt(len);
            byte[] lenArray = bb.array();
            for (byte b: lenArray) {
                byteList.add(b);
            }
            byte[] strArray = str.getBytes();
            for (byte b: strArray) {
                byteList.add(b);
            }
        }
        byte[] result = new byte[byteList.size()];
        for (int i=0; i<byteList.size(); i++) {
            result[i] = byteList.get(i);
        }
        return result;
    }

    public static String[] unserialize(byte[] bytes) {
        ArrayList<String> strList = new ArrayList<String>();
        for (int i=0; i< bytes.length;) {
            byte[] lenArray = new byte[4];
            for (int j=i; j<i+4; j++) {
                lenArray[j-i] = bytes[j];
            }
            ByteBuffer wrapped = ByteBuffer.wrap(lenArray);
            int len = wrapped.getInt();
            byte[] strArray = new byte[len];
            for (int k=i+4; k<i+4+len; k++) {
                strArray[k-i-4] = bytes[k];
            }
            strList.add(new String(strArray));
            i += 4+len;
        }
        return strList.toArray(new String[strList.size()]);
    }

    public static void main(String[] args) {
        String[] input = {"This is","a serialization problem;","string concatenation will do as well","in some cases."};
        byte[] byteArray = serialize(input);
        String[] output = unserialize(byteArray);
        for (String str: output) {
            System.out.println(str);
        }
    }
}

The idea is that in the resulting byte array we store the length of the first string(which is always 4 bytes if we use the type int), followed by the bytes of the first string(whose length can be read later from the preceding 4 bytes), then followed by the length of the second string and the bytes of the second string, and so on. This way, the string array can be recovered easily from the resulting byte array, as demonstrated by the code above. And this serialization approach can handle any situation.

And the code can be much simpler if we make an assumption to the input string array:

public class Concatenation {
    public static byte[] concatenate(String[] strs) {
        StringBuilder sb = new StringBuilder();
        for (int i=0; i<strs.length; i++) {
            sb.append(strs[i]);
            if (i != strs.length-1) {
                sb.append("*.*"); //concatenate by this splitter
            }
        }
        return sb.toString().getBytes();
    }

    public static String[] split(byte[] bytes) {
        String entire = new String(bytes);
        return entire.split("\\*\\.\\*");
    }

    public static void main(String[] args) {
        String[] input = {"This is","a serialization problem;","string concatenation will do as well","in some cases."};
        byte[] byteArray = concatenate(input);
        String[] output = split(byteArray);
        for (String str: output) {
            System.out.println(str);
        }
    }
}

The assumption is that *.* does not exist in any string from the input array. In other words, if you know in advance some special sequence of symbols won't appear in any string of the input array, you may use that sequence as the splitter.

Terry Li
  • 16,870
  • 30
  • 89
  • 134
-1

You can iterate for each string and keep appending to the final byte array.

String example = "This is an example";
//Convert String to byte[] using .getBytes() function
byte[] bytes = example.getBytes();
//Convert byte[] to String using new String(byte[])      
String s = new String(bytes);
Gary
  • 13,303
  • 18
  • 49
  • 71
sumeet kumar
  • 2,628
  • 1
  • 16
  • 24