V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
jzq526
V2EX  ›  Java

为什么 IDEA 显示结果为乱码而命令行窗口不会?

  •  
  •   jzq526 · 2018-10-26 16:01:13 +08:00 · 2395 次点击
    这是一个创建于 1981 天前的主题,其中的信息可能已经有所发展或是发生改变。

    最近在学习如何在 Java 程序中调用系统中的命令,程序如下: public static void main(String[] args) { String cmd="ipconfig"; Runtime run=Runtime.getRuntime(); try { Process process=run.exec(cmd); InputStream in=process.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String s = null; while ((s = reader.readLine()) != null) { System.out.println(s); } in.close(); process.waitFor(); }catch (IOException e){ e.printStackTrace(); }catch (InterruptedException e){ e.printStackTrace(); }

    }
    

    在 IDEA 中直接运行的时候,汉字部分显示为乱码,但在命令行中运行该程序却能正确显示汉字。 应该是两个环境的字符编码不同导致,该如何修改才能让 IDEA 能够正确显示汉字?

    4 条回复    2018-10-26 16:12:37 +08:00
    lihongjie0209
        1
    lihongjie0209  
       2018-10-26 16:08:08 +08:00   ❤️ 1
    BufferedReader reader = new BufferedReader(new InputStreamReader(in, "GBK"));

    指定编码
    lihongjie0209
        2
    lihongjie0209  
       2018-10-26 16:11:20 +08:00
    在 Stream 转 reader 的时候需要指定编码, 如果不指定, 那么就会使用一个 JVM 默认的编码, 判断逻辑在:


    public static Charset defaultCharset() {
    if (defaultCharset == null) {
    synchronized (Charset.class) {
    String csn = AccessController.doPrivileged(
    new GetPropertyAction("file.encoding"));
    Charset cs = lookup(csn);
    if (cs != null)
    defaultCharset = cs;
    else
    defaultCharset = forName("UTF-8");
    }
    }
    return defaultCharset;
    }


    如果在 windows 下不指定编码, 那么最后你解码出来的 reader 就是使用 utf-8 解码的, 但是 windows 输出的流是 GBK 编码, 编码和解码的方式不同就会导致乱码
    jzq526
        3
    jzq526  
    OP
       2018-10-26 16:11:33 +08:00
    @lihongjie0209 非常感谢,我只关注如何处理获取到的数据了,没想到可以在获取时就进行处理。这种方式在 IDEA 和命令行中都可以正确显示汉字了
    lihongjie0209
        4
    lihongjie0209  
       2018-10-26 16:12:37 +08:00
    @jzq526 永远不要使用系统默认的值, 特别是编码, 不然跨平台运行的时候都是坑
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2450 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 15:52 · PVG 23:52 · LAX 08:52 · JFK 11:52
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.