如何从Windows上的Java控制台应用程序确定当前活动的代码页? [英] How to determine the currently active code page from a Java console application on Windows?

查看:143
本文介绍了如何从Windows上的Java控制台应用程序确定当前活动的代码页?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个简单的Java应用程序,可在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"
    }
}

在我的Windows 10计算机上,此应用程序始终显示活动代码页:437" ,因为 Cp437 是默认设置,并且Runtime.getRuntime().exec()在以下情况下启动新的Process正在运行chcp.com.

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.

是否可以创建一个Java应用程序,而不是在其中运行代码的现有命令提示符窗口中显示当前活动的代码页?

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".

如何指定与基础Windows代码页一致的Java file.encoding值?问了类似的问题,但是在那种情况下,OP正在寻求一种非Java解决方案.

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.

我更喜欢仅使用Java的解决方案,但可以选择:

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

  • 是否可以使用JNI通过调用一些可以访问Windows API的C/C ++/C#代码来完成此操作?被调用的代码仅需要为活动代码页返回一个数字值.
  • 我会接受一个有说服力的论点,认为这样做是不可能的.

推荐答案

该解决方案仅是一行代码. 使用JNA ,这是Windows API函数

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

这篇关于如何从Windows上的Java控制台应用程序确定当前活动的代码页?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆