一般的我們使用byte接收讀取到的數據,若數據沒有達到byte定義的大小時,我們直接將byte轉換為String則會出現亂碼的情況,在這種情況下應該基于read的返回值來轉換byte,否則將產生亂碼的情況,
下面是一個簡單的示例:
1
2
3
4
5
6
7
8
9
10
|
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" )); } } |
輸出結果
1
2
3
|
please input something: asdfasdf you input is:asdfasdf |
以上這篇java 將byte中的有效長度轉換為String的實例代碼就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。