byte array to String in Android

社会主义新天地 提交于 2019-12-12 03:08:31

问题


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/



来源:https://stackoverflow.com/questions/9451521/byte-array-to-string-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!