Search code examples
javastringbyteencode

How to encode bytes to a string in Java


I am trying to encode bytes from an inputstream to plain text characters. So, I made the string out of ints seperated by spaces, like this:

InputStream in;
//etc
int b;
String finalString="";
while((b=in.read())!=-1)finalString+=""+b+" ";
in.close()

But the problem is, this makes the string 3-4 times larger than the original bytes. Is there any other way of encoding bytes to plain text?


Solution

  • If I understand correctly, you want to transform binary data into plain text. You should use Base64 for that. The loss factor will only be 4/3.

    Apache commons-codec has a free implementation of a Base64 encoder (and decoder).

    Another possibility is Hex encoding (which commons-codec also supports), but it needs 2 bytes of text for each byte of binary data.