You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Windows下Java终端UTF-8字符输入读取异常问题求助

Windows下Java读取UTF-8控制台输入异常的解决方案

问题本质

Windows默认控制台(Cmd、PowerShell、VSCode内置终端)在UTF-8模式(chcp 65001)下,与Java输入流交互存在兼容性问题:控制台会以UTF-16LE编码传递输入字节,但Java按UTF-8解析时会导致非ASCII字符丢失或乱码。而IntelliJ终端、WSL Bash采用了独立的终端实现,不存在该适配问题。

解决方案

1. 使用System.console()读取输入

System.console()直接调用Windows Unicode控制台API,能绕过输入流编码适配问题,正确读取UTF-8字符。替换原有代码为:

import java.io.Console;
import java.util.Arrays;
import java.nio.charset.StandardCharsets;

public class Main {
    public static void main(String[] args) {
        Console console = System.console();
        if (console == null) {
            System.err.println("请直接在终端中运行该程序,无法通过IDE内部控制台执行");
            System.exit(1);
        }
        System.out.println("Enter some text (UTF-8 characters supported):");
        String userInput = console.readLine();
        
        System.out.println("You entered: " + userInput);
        byte[] bytes = userInput.getBytes(StandardCharsets.UTF_8);
        System.out.println(Arrays.toString(bytes));
    }
}

2. 适配Windows控制台的UTF-16LE输入编码

如果必须使用InputStreamReader,可针对Windows系统强制按UTF-16LE解析输入(仅适用于Windows环境):

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        try {
            // 判断当前系统是否为Windows
            String os = System.getProperty("os.name").toLowerCase();
            StandardCharsets inputCharset = os.contains("win") 
                ? StandardCharsets.UTF_16LE 
                : StandardCharsets.UTF_8;
            
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(System.in, inputCharset)
            );
            System.out.println("Enter some text (UTF-8 characters supported):");
            String userInput = reader.readLine();
            
            System.out.println("You entered: " + userInput);
            byte[] bytes = userInput.getBytes(StandardCharsets.UTF_8);
            System.out.println(Arrays.toString(bytes));

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

3. 更换为Windows Terminal

Windows Terminal对UTF-8的支持更完善,可彻底解决终端与Java的编码适配问题:

  • 从微软商店安装Windows Terminal
  • 在VSCode中打开设置,搜索terminal.integrated.defaultProfile.windows,将默认终端设置为Windows Terminal(如"Windows PowerShell"或"Command Prompt")
  • 重启VSCode终端,执行chcp 65001后再运行Java程序

4. 添加Java启动参数

尝试添加-Dconsole.encoding=UTF-8启动参数,强制Java控制台编码为UTF-8:

java -Dconsole.encoding=UTF-8 Main

验证说明

  • 预设字符串能正常打印,说明Java的输出编码已正确设置为UTF-8
  • IntelliJ和WSL Bash正常工作,是因为它们的终端实现直接支持UTF-8输入输出,无需额外适配

内容的提问来源于stack exchange,提问作者Ádám

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 18:57:31