0

ByteArrayOutputStream を使用して、IputStream からテキスト ビューにテキストを配置しています。これは問題なく動作しますが... 私はスウェーデン出身で、特別なスウェーデン文字を含むテキストを入力すると、 ? と表示されます。実際の手紙の代わりに。それ以外の場合、システムはこの文字に問題はありません。誰かが私に何をすべきかについてのヒントを教えてくれることを願っています。

おそらく、コードを示します。

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    TextView helloTxt = (TextView)findViewById(R.id.hellotxt);
    helloTxt.setText(readTxt());
}

 private String readTxt(){
 InputStream inputStream = getResources().openRawResource(R.raw.hello);
 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
 int i;
 try {
 i = inputStream.read();
 while (i != -1)
  {
   byteArrayOutputStream.write(i);
   i = inputStream.read();
  }
  inputStream.close();
} catch (IOException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
}

 return byteArrayOutputStream.toString();
}
}

私もこれを結び、フォーラムから入手しました(Selzier):ナイスピースですが、出力にスウェーデン語の文字はまだありません:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    TextView tv = (TextView)findViewById(R.id.txtRawResource);  
    tv.setText(readFile(this, R.raw.saga));
}

private static CharSequence readFile(Activity activity, int id) {
    BufferedReader in = null;
    try {
        in = new BufferedReader(new InputStreamReader(
                activity.getResources().openRawResource(id)));
        String line;
        StringBuilder buffer = new StringBuilder();
        while ((line = in.readLine()) != null) buffer.append(line).append('\n');
        return buffer;
        } 
    catch (IOException e) {
        return "";
    } 
    finally {
        closeStream(in);
    }
}

/**
 * Closes the specified stream.
 */
private static void closeStream(Closeable stream) {
    if (stream != null) {
        try {
            stream.close();
        } catch (IOException e) {
            // Ignore
        }
    }
}
}
4

1 に答える 1

0

ストリームを読み書きするときに、間違ったエンコーディングを使用しています。を使用しUTF-8ます。

 outputStream.toString("UTF8")

編集:ここに投稿されたこのアプローチを試してください。ファイルにBOMがある場合も問題になると思います。NotePad++ または別のエディターを使用して削除します。

 public static String readRawTextFile(Context ctx, int resId)
 {
     InputStream inputStream = ctx.getResources().openRawResource(resId);

     InputStreamReader inputreader = new InputStreamReader(inputStream);
     BufferedReader buffreader = new BufferedReader(inputreader);
     String line;
     StringBuilder text = new StringBuilder();

     try {
         while (( line = buffreader.readLine()) != null) {
            text.append(line);
            text.append('\n');
         }
     } catch (IOException e) {
         return null;
     }
     return text.toString();
 }
于 2011-09-10T19:00:57.167 に答える