Generally, we use byte to receive the read data. If the data does not reach the size defined by byte, we will directly convert byte to String and then there will be garbled code. In this case, byte should be converted based on the return value of read, otherwise garbled code will occur.
Here is 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")); } }Output result
please input something: asdfasdf you input is:asdfasdf
The above example code for converting the effective length in byte into String is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.