how to use chinese and japanese character as string in java?
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
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 物().処理();
Just use it, Java Strings are fully unicode, so there should be nothing hard to just say
System.out.println("世界您好!");
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).