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

被刻印的时光 ゝ 提交于 2019-11-26 09:12:11

问题


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



来源:https://stackoverflow.com/questions/4067628/how-to-use-chinese-and-japanese-character-as-string-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!