Convert byte array to string without using new operator in Java

Is there a way to convert an array of bytes to a string other than new String(bytearray)? The exact problem is that I am passing the json formatted string over the network through a UDP connection. On the other hand, I get it in a fixed-size byte array (since I don't know the size of the array) and create a new row from the byte array. If I do this, all the memory that I have allocated is not needed.

To avoid this, I get an array of bytes that converts it to a string, truncates the string to the last valid character, and then converts it to an array of bytes and creates a new string from it. If I do, it just uses the required memory, but the frequency of garbage collection becomes so high that it requires more allocations. What is the best way to do this?

+3
source share
4 answers

There will be something like:

String s = new String( bytearray, 0, lenOfValidData, "US-ASCII");

do what you want (change encoding to any encoding)?


Update:

Based on your comments, you can try:

socket.receive(packet);
String strPacket = new String( packet.getData(), 0, packet.getLength(), "US-ASCII");
receiver.onReceive( strPacket);

Java, , packet.getLength() ( , ). , :

String strPacket = new String( packet.getData(), 
                               0, 
                               Math.min( packet.getLength(), packet.getData().length),
                               "US-ASCII");

.

+2

- , UDP. Javadoc DatagramSocket.receive(...) :

. , DatagramPacket . IP- -.

. . , .

, .

  byte[] buff = ... // read from socket.

  // Find byte offset of first 'non-character' in buff
  int i;
  for (i = 0; i < buff.length && /* buff[i] represents a character */; i++) { /**/ }

  // Allocate String
  String res = new String(buff, 0, i, charsetName);

, . , , .

javadoc : " , , ."

, (, UTF-8, UTF-16, JIS ..) . , , 10 UTF-8 10 .

+2

, StringBuilder. , :

  • ( ) .
  • StringBuilder.
  • , StringBuilder.
  • . ( , - , .)

Tofubeer StringBuilder StringBuffer.

0

Can you write the input stream to ByteArrayOutputStreamfirst and then output toStringto the output stream? So something like this:

ByteArrayOutputStream os = new ByteArrayOutputStream();
while (!socket.isClosed()) {
    InputStream is = socket.getInputStream();
    byte[] buffer = new byte[1024]; // some tmp buffer.  Define the appropriate size here
    int bytesRead;
    while ((bytesRead = is.read(buffer)) != -1) {
        baos.write(buffer, 0, bytesRead);
        if (is.available() <= 0) {
            break;
        }
    }
    System.out.println(baos.toString());
    baos.reset();
}
0
source

Source: https://habr.com/ru/post/1753973/


All Articles