Burak Esen
Burak Esen

Reputation: 58

Why some ASCII and Unicode characters cannot write to the command prompt with java?

I try to write a console Card game with java. and I have to use these ♥ ♦ ♣ ♠ characters. But when I start the program on command prompt characters look like ? ? ? ? . I try Unicode and ASCII and I got the same results. I use intellij idea. and I can write these Ascii characters 217┘ 218┌ 191┐ 192└ 196─

I try to print them like

System.out.println("♥")

or

System.out.println(Character.toString('\u2661'))

Unicode characters \u2661 ... and so on. ASCII 3 4 5 6

It works on Intellij Idea terminal. when I try to write manually on command prompt alt+3, I can write ♥ but when starting the game it looks like ?

here a png of my default encoding.xml

here output of Inellij console

and here output of cmd console

───────────────────────────────────────────────

Edit:

try {
        if (System.getProperty("os.name").contains("Windows")){
            new ProcessBuilder("cmd", "/c", "chcp 65001").inheritIO().start().waitFor();
        }
} catch (IOException | InterruptedException ex) {}

Upvotes: 0

Views: 728

Answers (2)

andrewJames
andrewJames

Reputation: 21910

Assuming you are trying to print using System.out, then try this:

import java.io.PrintStream;
import static java.nio.charset.StandardCharsets.UTF_8;

public class App {

    public static void main(String[] args) {
        System.out.println("First attempt: ♣");
        PrintStream out = new PrintStream(System.out, true, UTF_8);
        out.println("Second attempt: ♣");
    }
}

In my environment, this prints the following output:

First attempt:  ?
Second attempt: ♣

In some cases this may still not be sufficient, depending on how you are running your code. For example if you are running it inside NetBeans, then the following may need to be added to the Netbeans start-up options:

-Dfile.encoding=UTF-8

Upvotes: 0

rzwitserloot
rzwitserloot

Reputation: 102902

All you really needed to paste was System.out.println("♥"), the rest is irrelevant.

There isn't enough information in your question for a proper answer. I think it is one of these three:

[1] your file is in some charset encoding (say, UTF-8), but the javac run that makes the class file is configured with -encoding ISO-8859-1 or something else that isn't UTF-8. If you're letting intellij compile it for you I kinda doubt this is it.

[2] the console that you're running this in (the console view of intellij, perhaps), also has a charset encoding and it is not UTF_8.

[3] it's UTF-8 all the way down, but, the font used to render it doesn't have the symbol available to it. This is also unlikely; the usual way to render a missing character is a box, or a diamond with a question mark inside, not a plain ?. Or is that what you see?

Upvotes: 2

Related Questions