Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Store byte array as String in DB and create byte array using String value

I have a byte array with the value [B@6c89db9a I have stored this value in a MySQL db as a string representation - mybyteArray.toString()

I would like to retrieve the saved value from the database and create a new byte array using the string value of the original byte array.

I have tried the examples Java Byte Array to String to Byte Array

and byte to string and vice versa

However i am not getting the original byte array value. It is generating a different value. Can anyone please advise?

like image 411
Santiago Avatar asked Dec 06 '22 06:12

Santiago


1 Answers

I have a byte array with the value [B@6c89db9a I have stored this value ...

That's not a value. It's a completely useless (outside of Java) hashcode. The toString() method of an array does not print the contents of an array. Arrays do not override toString() and therefore Object.toString() is called.

If you wish to store an array of arbitrary bytes in MySQL you would want to use a BLOB type (or maybe VARBINARY? it's been a while since I've used MySQL but it appears from a quick google they're basically the same in modern versions) in your table, and store the bytes:

create table example (some_bytes BLOB);

Your prepared statement would look like:

String query = "INSERT INTO example (some_bytes) VALUES (?)";
PreparedStatement pstmt = conn.prepareStatement(query);

And you'd insert those bytes via:

pstmt.setBytes(1, myByteArray);
pstmt.execute();

Edit to add from comments: You have some bytes in an array. If those bytes represent a string of characters and you know what the character set is, you convert them to a String using the String constructor that takes a character set:

String myString = new String(bytes, knownCharset); 

For example, if they represent a UTF-8 string you would use:

String myString = new String(byteArray, Charset.forName("UTF-8"));
like image 170
Brian Roach Avatar answered Dec 11 '22 09:12

Brian Roach