2016-11-16 4 views
0

urlの内容はUTF-8ですが、system.outの文字列はUTF-8ではありません。どのようにしてutf-8をサポートするように文字列を変換できますか?urlの内容はUTF-8ですが、system.outの文字列がUTF-8ではない場合

Objectgeörienteerd 

私はバイト配列、入力ストリームなどのようなことを試みましたが、うまくいきませんでした。

マイコード:

HttpURLConnection connection = null; 
String thatUrl = url[0]; 
URL urly = new URL(thatUrl); 
InputStream is = urly.openStream(); 
final StringBuffer buffer = new StringBuffer(); 
int counter; 
while ((counter = is.read()) != -1) { 
    buffer.append((char) counter); 
} 
+0

buffer.toString()を使用できます。 PrintStream out = new PrintStream(System.out、true、 "UTF-8")を試すこともできます。 out.println(バッファ);それはエンコーディングの設定を可能にするからです。 –

+0

@ JohnMorrisonこれは問題とは関係ありません。 – Kayaman

答えて

4

あなたはis.read()に一度の内容1つのバイトを読んでいます。 UTF-8の一部の文字は1バイト以上です。これらの文字のいずれかが出現するたびに、それぞれのバイトをそれぞれcharに変換することで文字を破ります。

簡単な解決策は、(ByteArrayOutputStreamを使用して、たとえば)byte[]に内容を読んで、あなたはすべてのバイトを持っているとき、new String(byteArray, "UTF-8");Stringに変換することです。

ByteArrayOutputStream out = new ByteArrayOutputStream(); 
int counter; 
byte[] buffer = new byte[1024]; // Let's read up to 1KB at a time, it's faster 
while((counter = is.read(buffer)) != -1) 
    out.write(buffer, 0, counter); 

// String output = new String(out.toByteArray(), "UTF-8"); 
String output = out.toString("UTF-8"); // Save an extra byte[] allocation 
+0

うまくいきません:( – Jason

+0

私のコードがうまくいかない場合、それはちょうど ':('。( – Kayaman

+0

)よりも深刻です。残念ながらそれはうまくいきません。奇妙な文字として – Jason

関連する問題