byte array to String in Android

2019-09-01 14:29发布

问题:

I need a way to convert a byte[] to a String without creating a new String object.

What I don't want:

String s= new String(byte[], int offset, int byteCount);

Is there another way to achieve the same thing without creating a new String object?

I've been looking at Base64 class. Does that work?

回答1:

This would only be possible if somewhere you had a cache of the strings generated from every input you're going to get.

Strings are immutable, so you can't put the new data into an existing string - so unless you can find an existing string which already has the right data (the cache I mentioned before) you'll have to create a new string.

(I would also strongly recommend that you specify the character encoding you want to use, instead of relying on the system default encoding.)

Of course, if this isn't genuinely encoded text to start with (e.g. if the byte[] data is from an image) then Base64 would be more appropriate anyway - but that's orthogonal from whether or not you need a new string.



回答2:

just put Base64.java file in your project package. & use String str = Base64.encodeBytes(byte array); which will give u byte[] to string conversion. you can download base64.java from http://iharder.sourceforge.net/current/java/base64/