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

问题描述 投票:0回答:1

这是一个简单的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的解决方案,但作为替代方案:

  • 这可以通过调用一些可以访问Windows API的C / C ++ / C#代码使用JNI来完成吗?被调用的代码只需返回活动代码页的数值。
  • 我会接受一个有说服力地争辩说无法完成的答案。
java windows jna windows-console codepages
1个回答
1
投票

解决方案只是一行代码。 Using JNA,Windows API函数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

© www.soinside.com 2019 - 2024. All rights reserved.