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.