How to determine the currently active code page from a Java console application on Windows?

自闭症网瘾萝莉.ら 提交于 2019-12-13 10:23:31

问题


This is a simple Java application which displays the default code page on 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"
    }
}

On my Windows 10 machine this application always displays "Active code page: 437" because Cp437 is the default, and Runtime.getRuntime().exec() starts a new Process when running chcp.com.

Is it possible to create a Java application which instead displays the currently active code page for the existing Command Prompt window in which the code is running?

I want to be able to do something like this from the Command Prompt:

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? asked a similar question, though in that case the OP was seeking a non-Java solution.

I'd prefer a Java-only solution, but as alternatives:

  • Can this possibly be done using JNI, by calling some C/C++/C# code with access to the Windows API? The called code need only return a numeric value for the active code page.
  • I'll accept an answer which persuasively argues that it can't be done.

回答1:


The solution turned out to be just one line of code. Using JNA, the value returned by the Windows API function GetConsoleCP() gives the console's active code page:

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();
    }
}



来源:https://stackoverflow.com/questions/54838263/how-to-determine-the-currently-active-code-page-from-a-java-console-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!