代码之家  ›  专栏  ›  技术社区  ›  skomisa

如何从Windows上的Java控制台应用程序确定当前活动的代码页?

  •  0
  • skomisa  · 技术社区  · 6 年前

    这是一个简单的Java应用程序,它显示 在Windows上:

    package doscommand;
    
    import java.io.IOException;
    import java.io.InputStream;
    
    public class DosCommand {
    
        public static void main(String[] args) throws IOException {
    
            InputStream in = Runtime.getRuntime().exec("chcp.com").getInputStream();
            int ch;
            StringBuilder chcpResponse = new StringBuilder();
            while ((ch = in.read()) != -1) {
                chcpResponse.append((char) ch);
            }
            System.out.println(chcpResponse); // For example: "Active code page: 437"
        }
    }
    

    在我的Windows 10计算机上,此应用程序始终显示 “活动代码页:437” Cp437型 是默认值,并且 Runtime.getRuntime().exec() Process 运行时 chcp.com .

    是否可以创建一个Java应用程序来显示 当前活动代码页 对于现有的 命令提示符

    我想从 命令提示符

    chcp 1252
    java -jar "D:\NB82\DosCommand\dist\DosCommand.jar" REM Shows current code page is "1252".
    
    chcp 850
    java -jar "D:\NB82\DosCommand\dist\DosCommand.jar" REM  Shows current code page is "850".
    

    How do you specify a Java file.encoding value consistent with the underlying Windows code page? 问了一个类似的问题,尽管在这种情况下,OP正在寻找一个非Java的解决方案。

    我更喜欢纯Java的解决方案,但作为替代方案:

    • 这可以通过使用JNI调用一些C/C++ +C代码来访问Windows API吗?调用的代码只需要为活动代码页返回一个数值。
    • 我会接受一个有说服力的回答,认为这是做不到的。
    0 回复  |  直到 6 年前
        1
  •  1
  •   skomisa    6 年前

    结果证明解决方案只是一行代码。 Using JNA GetConsoleCP() 提供控制台的活动代码页:

    import com.sun.jna.platform.win32.Kernel32;
    
    public class JnaActiveCodePage {
    
        public static void main(String[] args) {
            System.out.println("" + JnaActiveCodePage.getActiveInputCodePage());
        }
    
        /**
         * Calls the Windows function GetConsoleCP() to get the active code page using JNA.
         * "jna.jar" and "jna-platform.jar" must be on the classpath.
         *
         * @return the code page number.
         */
        public static int getActiveInputCodePage() {
            return Kernel32.INSTANCE.GetConsoleCP();
        }
    }
    

    chcpDemo