Is there a way to convert a byte array to string other than using new String(bytearray)? The exact problem is I transmit a json-formatted string over the network through UDP connection. At the other end, I receive it in a fixed-size byte array(as I am not aware of the array size) and create a new string out of the byte array. If I do this, the whole memory that I allocated is being held unnecessary.
To avoid this I get the byte array convert it to string, truncate the string till the last valid character and then convert it to a byte array and create a new string out of it. If I do this, it just uses up the required memory but the garbage collection frequency becomes so high as it involves more number of allocations. What is the best way to do this?
Would something like:
do what you want (change the charset to whatever encoding is appropriate)?
Update:
Based on your comments, you might want to try:
I’m not familiar enough with Java’s datagram support to know if
packet.getLength()returns the truncated length or the original length of the datagram (before truncation to fit in the receive buffer). It might be safer to create the string like so:Then again, it might be unnecessary.