Eclipse 控制台運行 Java 程序,輸入中文時:有時正常,有時拋異常,輸入文本不變綠,光標位置異常。
System.in 是 字節流,漢字在 UTF-8 下佔 3 字節,直接 read() 或 Scanner.next() 會按字節切分,導致字符不完整、解碼錯誤、光標渲染異常。
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class ConsoleInputDemo {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in, "UTF-8"));
System.out.print("請輸入:");
String line = br.readLine(); // 按行讀取,自動處理編碼
System.out.println("您輸入:" + line);
}
}
new InputStreamReader(System.in, "UTF-8") 與控制台編碼一致(Eclipse 默認 UTF-8,可在 Run Configurations → Common → Encoding 確認)。readLine() 遇換行符返回完整字符串,避免半個漢字問題。Scanner.next() 以空白分隔,中文無空格會整行讀入,但內部仍用字節流,易出問題;建議 Scanner.nextLine() 配合 useDelimiter(\\n)。