jzq526
V2EX  ›  Java

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

  •  
  •   jzq526 · Oct 26, 2018 · 3024 views
    This topic created in 2760 days ago, the information mentioned may be changed or developed.

    最近在学习如何在 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 replies    2018-10-26 16:12:37 +08:00
    lihongjie0209
        1
    lihongjie0209  
       Oct 26, 2018   ❤️ 1
    BufferedReader reader = new BufferedReader(new InputStreamReader(in, "GBK"));

    指定编码
    lihongjie0209
        2
    lihongjie0209  
       Oct 26, 2018
    在 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
       Oct 26, 2018
    @lihongjie0209 非常感谢,我只关注如何处理获取到的数据了,没想到可以在获取时就进行处理。这种方式在 IDEA 和命令行中都可以正确显示汉字了
    lihongjie0209
        4
    lihongjie0209  
       Oct 26, 2018
    @jzq526 永远不要使用系统默认的值, 特别是编码, 不然跨平台运行的时候都是坑
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2877 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 11:01 · PVG 19:01 · LAX 04:01 · JFK 07:01
    ♥ Do have faith in what you're doing.