代码之家  ›  专栏  ›  技术社区  ›  Epaga Alex Reynolds

Java:如何检测(并更改)System.console的编码?

  •  17
  • Epaga Alex Reynolds  · 技术社区  · 15 年前

    我有一个在控制台上运行的程序,它的元音和其他特殊字符在Macs上被输出为?'s。下面是一个简单的测试程序:

    public static void main( String[] args ) {
        System.out.println("höhößüä");
        System.console().printf( "höhößüä" );
    }
    

    在默认的Mac控制台(使用默认的UTF-8编码)上,打印:

     h?h????
     h?h????
    

    但在手动将Mac终端的编码设置为“macos-Roman”之后,它就正确地打印出来了

     höhößüä
     höhößüä
    

    请注意,在使用System.console()的Windows系统上:

     h÷h÷▀³õ
     höhößüä
    

    那么我该如何制作我的程序。。。 滚眼

    2 回复  |  直到 15 年前
        1
  •  10
  •   gamma    15 年前

    here . 您可以在printstream中设置输出编码—只需确定或绝对确定要设置哪个。

    import java.io.PrintStream;
    import java.io.UnsupportedEncodingException;
    
    public class Test {
        public static void main (String[] argv) throws UnsupportedEncodingException {
        String unicodeMessage =
        "\u7686\u3055\u3093\u3001\u3053\u3093\u306b\u3061\u306f";
    
        PrintStream out = new PrintStream(System.out, true, "UTF-8");
        out.println(unicodeMessage);
      }
    }
    

    LANG="de_DE.UTF-8"
    LC_COLLATE="de_DE.UTF-8"
    LC_CTYPE="de_DE.UTF-8"
    LC_MESSAGES="de_DE.UTF-8"
    LC_MONETARY="de_DE.UTF-8"
    LC_NUMERIC="de_DE.UTF-8"
    LC_TIME="de_DE.UTF-8"
    LC_ALL=
    
        2
  •  13
  •   Bozho    15 年前

    启动应用程序时,请尝试以下命令行参数:

    -Dfile.encoding=utf-8

    这将更改用于I/O操作的JVM的默认编码。

    System.setOut(new PrintStream(System.out, true, "utf-8"));