I have a byte array which contains text padded with values 0 up to fill 16 bytes.
When I try to convert it to String I can not get the right length/String, it always retrieves the whole 16 characters.
I have tried:
import java.nio.charset.StandardCharsets;
public class HelloWorld{
public static void main(String []args){
// SIMULATED BYTE[] CONTAINS "ABC" PLUS CHAR(0) UNTIL FILL 16 BYTES
byte[] name = new byte[16];
for(int i=0; i<16; i++) {
name[i] = 0;
}
name[0] = 'A';
name[1] = 'B';
name[2] = 'C';
// DESIRED OUTPUT IS A STRING = "ABC".
// I.E. REMOVAL OF PADDING WITH CHAR(0)s
String nameStr = new String(name, StandardCharsets.US_ASCII);
System.out.println("#"+nameStr+"#");
System.out.println(nameStr.length());
}
}
This is the output:
The desired retrieved length is 3, not 16. Also it can be seen in NetBeans output how the String contains the padding 0 values.
I am using OpenJDK8 under FreeBSD and NetBeans 11.