Search code examples
javawindowsjnawindows-consolecodepages

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


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.

Solution

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

    chcpDemo