java converts the effective length in byte to the instance code of String


If the data does not reach the size defined by byte, we will directly convert byte to String, and there will be scrambled codes. In this case, byte should be converted based on the return value of read. Otherwise, there will be scrambled codes.

Here’s a simple example:

package com.javaio.myinputstream;

public class MyConsole {
  public static void main(String argv[]) throws Exception {
    System.out.println("please input something:");
    byte[] b = new byte[1024];
    int len = System.in.read(b);
    System.out.println("you input is:" + new String(b, 0, len, "UTF-8"));
  }
}

The output

please input something:
asdfasdf
you input is:asdfasdf