2

かなり簡単な質問があります。ストリームから文字列を読み取るとき、記号を除いてすべての文字で問題ありません。たとえば、™または©記号が含まれているユーザー名を読み込もうとすると、記号はそれぞれâ„¢および©として出力されます。JavaはすべてのUnicode文字をサポートしていると思いました。シンボルを正しく印刷するにはどうすればよいですか?

私が使用できる特別なタイプの文字列、またはおそらくこの問題に対する別の解決策はありますか?

4

2 に答える 2

2

ストリームから読み取る場合、たとえば次のように使用します

InputStreamReader reader = new InputStreamReader(stream);

プラットフォームエンコーディングを使用するようにJavaに指示します。これは、Unicode エンコーディングではない可能性があります (実際、Windows PC が表示される頻度を考えると、少なくとも 50% の時間)。

バイトストリームのエンコーディングを指定する必要があります。

InputStreamReader reader = new InputStreamReader(stream, charset);

または

InputStreamReader reader = new InputStreamReader(stream, "UTF-8");

Charset インスタンスではなく文字セット名を使用する場合

于 2012-09-19T00:09:19.850 に答える
0

Based on the character examples you are giving, I believe you are reading in the characters correctly. For example, the copyright character is Unicode A9. When you write it out in UTF-8 however, it will be serialized as 2 bytes: C2 followed by A9. See http://www.fileformat.info/info/unicode/char/a9/index.htm

If your output device expects data in UTF-8 format all will be well. However since you are seeing ©, I believe your output device expects data in ISO-8859-1 (see http://en.wikipedia.org/wiki/ISO/IEC_8859-1) so you have a mismatch. The output device interprets the C2 as  and the A9 as ©.

To fix this in code (without changing your output device) you need to create an print stream that will use the ISO-8859-1 character encoding when it converts your Unicode characters to a byte stream. For example:

public static void main (String [] args) throws Exception
{
    // use default character encoding
    String s = "copyright is ©";
    System.out.println(s);

    // create a new stream with a different encoding
    PrintStream out = new PrintStream(System.out, true, "ISO-8859-1");
    out.println(s);
}

In my case the first println looks good because the IDE console window has UTF-8 encoding and the second one looks bogus. In your case the first line should be bad (showing two characters where the copyright symbol should be) and the second one should show the correct copyright character.

于 2012-09-19T00:40:23.620 に答える