how to use chinese and japanese character as string in java?

60,236

Solution 1

Java Strings support Unicode, so Chinese and Japanese is no problem. Other tools (such as text editors) and your OS shell probably need to be told about it, though.

When reading or printing Unicode data, you have to make sure that the console or stream also supports Unicode (otherwise it will likely be replaced with question marks).

Writer unicodeFileWriter = new OutputStreamWriter(
    new FileOutputStream("a.txt"), "UTF-8");
unicodeFileWriter.write("漢字");

You can embed Unicode literals directly in Java source code files, but you need to tell the compiler that the file is in UTF-8 (javac -encoding UTF-8)

String x = "漢字";

If you want to go wild, you can even use Chinese characters in method, variable, or class names. But that is against the naming conventions, and I would strongly discourage it at least for class names (because they need to be mapped to file names, and Unicode can cause problems there):

結果 漢字 = new 物().処理();

Solution 2

Just use it, Java Strings are fully unicode, so there should be nothing hard to just say

System.out.println("世界您好!");

Solution 3

One more thing to remember, the Reader should be BufferedReader, and what I mean is:

BufferedReader br = new BufferedReader (new InputStreamReader (new FileInputStream (f), "UTF-8"));

this must be done because when you read the file, readLine() can be called:

while (br.readLine() != null)
{
  System.out.println (br.readLine());
}

This method is the only one that I found which can function normally because a regular Reader does not contain a non-static readLine() void method (this method does not accept anything).

Share:
60,236
sjain
Author by

sjain

Updated on June 14, 2020

Comments

  • sjain
    sjain almost 4 years

    Hi
    I am using java language. In this I have to use some chinese, japanese character as the string and print using System.out.println().

    How can I do that?

    Thanks

  • AlcubierreDrive
    AlcubierreDrive over 13 years
    Just make sure your source code files are Unicode encoded if you use non-ASCII constants.
  • hansvb
    hansvb over 13 years
    You may need to adjust the locale to support UTF-8 in System.out, and tell the compiler that your source file is in UTF-8.
  • sjain
    sjain over 13 years
    I do not have chinese character in my key board so what code I should write to get printed the chinese character.
  • hansvb
    hansvb over 13 years
    What OS are you using? You do not need a special keyboard, this is taking care of in software. For example I typed 漢字 as "kanji + SPACE". Also, copy/paste from a web browser or some other source works.
  • Paras Singh
    Paras Singh over 6 years
    What if the chinese characters are not in a file? I mean, is there any direct Unicode Writer that can handle that?