how to use chinese and japanese character as strin

2019-01-06 21:24发布

问题:

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

回答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 物().処理();


回答2:

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

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


回答3:

A bit outdated but it made me wow!

http://xahlee.org/java-a-day/unicode_in_java.html

The article is about variable naming bu from that you can tell it's sufficient to write your chinese/japanese string directly in your source.



回答4:

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



标签: java unicode cjk