Win a copy of Java by Comparison (eBook) this week in the Java in General forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

About creating string from Base64 encoded byte array and then invoking getBytes...  RSS feed

 
Rancher
Posts: 1369
1
Android Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If I have a Base64 encoded byte array(encoded using Base64.encodeBase64(..) method of org.apache.commons.codec.binary.Base64 class) and I create a String using this byte array:
String aString = new String(base64EncodedArray);
will the constructor affect the data in byte array or specifically hurt the encoding in any way?

If I do aString.getBytes() will the resulting byte array contain same byte stream as base64EncodedArray?

Thanks in advance.
 
Rancher
Posts: 42975
76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is easy enough to test with a few lines of code, but I think the answer is "yes" for both cases. Base-64 only uses non-control characters that are part of US-ASCII - those should have the same encoded values in just about any encoding.

As a rule of thumb, you shouldn't use new String(byte[]) and String.getBytes() without specifying the encoding; that's just asking for trouble.
 
Sheriff
Posts: 57778
178
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Too difficult a question for beginning Java. Moving.
 
Monu Tripathi
Rancher
Posts: 1369
1
Android Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

This is easy enough to test with a few lines of code, but I think the answer is "yes" for both cases. Base-64 only uses non-control characters that are part of US-ASCII - those should have the same encoded values in just about any encoding.

As a rule of thumb, you shouldn't use new String(byte[]) and String.getBytes() without specifying the encoding; that's just asking for trouble.



Ulf: Thank you for your reply.

I tested the equality of(==) encoded characters in byteArray and characters in the array returned by String.getBytes(). Both were equal.
I also tested this by writing image data in Byte array, encoding it and then use the String constructor, getting the bytes and again reconstructing the image back. The image was same with no distortion(difference).
So, I think it is safe to assume that encoding is not hurt, atleast in this case.

Also, thanks for your advice about String constructor usage.

Cheers!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!