Search code examples
javastringunicodeencoding

Java not printing Persian accurately in Windows command line


Here is my code:

class Hello{
    public static void main(String[] arg)throws Exception{
        System.out.println("Hello");
        String str = "سلام";
            System.out.println(new String(str.getBytes("UTF-8")));
    }
}

Compiling as: javac -encoding UTF8 Hello.java The ouput is:

C:\Users\Windows\Desktop>java Hello
Hello
ط³ظ„ط§ظ…

chcp shows: Active code page: 65001

How can I display it accurately?

Best Regards


Solution

  • Your code is fine, but you have two problems:

    • You are using a font in the Command Prompt window which does not properly support Farsi characters.
    • Farsi is written from right to left, but the Command Prompt window is rendering text from left to right, so even if you use an appropriate font the Farsi text will be rendered in reverse.

    Using your sample application, this is how the output was rendered in my Command Prompt window using Courier New font which supports Farsi characters:

    Farsi from cmd window

    Note that the characters were rendered correctly, but in reverse order.

    There may be an easy workaround to get characters to render right to left text correctly in a Command Prompt window, but a better alternative approach in any case is to instead use the Command Prompt implementation provided by the Microsoft's Terminal utility.

    If you do that then your application's output is rendered correctly without needing to make any configuration changes:

    Terminal output

    Notes:

    • My environment is Windows 10 using United States locale with a default code page of 65001. I tested using JDK 20, but any JDK version should be fine.
    • Unless you must use the traditional Command Prompt window for compatibility reasons, consider using the Command Prompt implementation provided by Terminal instead. All kinds of text rendering problems just disappear because some longstanding bugs/limitations with the traditional Command Prompt window have been resolved.
    • If you are not familiar with Terminal, this is Microsoft's overview description:

    Windows Terminal is a modern host application for the command-line shells you already love, like Command Prompt, PowerShell, and bash (via Windows Subsystem for Linux (WSL)). Its main features include multiple tabs, panes, Unicode and UTF-8 character support, a GPU accelerated text rendering engine, and the ability to create your own themes and customize text, colors, backgrounds, and shortcuts.