Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a String-represented ByteBuffer into a byte array in Java

Tags:

java

scala

I'm new to Java and I'm no sure how to do the following:

A Scala application somewhere converts a String into bytes:

ByteBuffer.wrap(str.getBytes)

I collect this byte array as a Java String, and I wish to do the inverse of what the Scala code above did, hence get the original String (object str above).

Getting the ByteBuffer as a String to begin with is the only option I have, as I'm reading it from an AWS Kinesis stream (or is it?). The Scala code shouldn't change either.

Example string:

String str = "AAAAAAAAAAGZ7dFR0XmV23BRuufU+eCekJe6TGGUBBu5WSLIse4ERy9............";

How can this be achieved in Java?

EDIT

Okay, so I'll try to elaborate a little more about the process:

  1. A 3rd party Scala application produces CSV rows which I need to consume
  2. Before storing those rows in an AWS Kinesis stream, the application does the following to each row:

    ByteBuffer.wrap(output.getBytes);
    
  3. I read the data from the stream as a string, and the string could look like the following one:

    String str = "AAAAAAAAAAGZ7dFR0XmV23BRuufU+eCekJe6TGGUBBu5WSLIse4ERy9............";
    
  4. I need to restore the contents of the string above into its original, readable, form;

I hope I've made it clearer now, sorry for puzzling you all to begin with.

like image 466
Yuval Herziger Avatar asked May 15 '26 02:05

Yuval Herziger


1 Answers

If you want to go from byte[] to String, try new String(yourBytes).

Both getBytes and the String(byte[]) uses the default character encoding.


From Amazon Kinesis Service API Reference:

The data blob to put into the record, which is Base64-encoded when the blob is serialized.

You need to base64 decode the string. Using Java 8 it would look like:

byte[] bytes = Base64.getDecoder().decode("AAAAAAAAAAGZ7dFR0XmV23BR........");
str = new String(bytes, "utf-8"));

Other options: Base64 Encoding in Java

like image 144
aioobe Avatar answered May 16 '26 16:05

aioobe