Special Character in Java

帅比萌擦擦* 提交于 2019-12-11 01:53:06

问题


How can i use special characters in java? They belong under the Cp1252 Character encoding. I try to use them in a message, but i cant use them.

Characters like: " ︻ー┳═デ "


回答1:


Use the associated UTF values, for example looking up 'デ' on http://www.fileformat.info/info/unicode/char/search.htm gives the value of \u30C7 so you can:

System.out.println( "\u30C7" );  // as string

System.out.println( '\u30C7' ); // as char



回答2:


You might wrap PrintWriter around System.out, to set charset explicitly.

final String charset = "UTF-8";
PrintWriter out = null;
try {
    out = new PrintWriter(new OutputStreamWriter(System.out, charset), true);
} catch(UnsupportedEncodingException e) {
    e.printStackTrace();
}

As for the ? as the character display - It really depends on where you're outputting standard out stream. In standard Ubuntu terminal - it would probably look good (I could test it later). On Windows' cmd however, you should manually set the codepage Chcp and provide a font that comes with those characters.

Same goes for Eclipse, its console charset is UTF-8 I believe, but if you have no fonts with Japanese characters, it won't help you much.




回答3:


When you use string literals with special characters inside Java code, you must also inform the Java compiler which encoding the Java file itself is encoded with.

Say you edited your Java file (containing the Japanese literal text) and saved it as a UTF-8 file. You must, then, tell the compiler to treat the source file as a UTF-8 document:

javac -encoding UTF-8 file1 file2 ...

Otherwise, the Java compiler will assume that the Java file is encoded using the operating system's default encoding, which isn't necessarily what you want it to do.



来源:https://stackoverflow.com/questions/12445635/special-character-in-java

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