0

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?

3
  • 4
    You want to create a String object, without creating it? :\ Commented Feb 26, 2012 at 8:09
  • Why do you think you need this? Commented Feb 26, 2012 at 8:11
  • Memory issues. I'm getting tons and tons of byte arrays that I need turned into strings. Garbage collection does not seem to work well because I get outofmemory errors after a while. Commented Feb 26, 2012 at 8:25

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

However, you can have a pool of Strings, and change them on the fly using reflection. I agree it is probably a terrible solution, and might cause havoc to the jvm.
@amit: You can change them on reflection if the security manager lets you. I don't know whether or not it does on Android, and I consider it such a bad solution that I wasn't going to mention it in the answer :)
Agreed. Just mentioned it is possible theoretically - for future readers. If I thaught it is actually a solution, I would have posted it as an answer.
0

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.