2011-09-10 22 views
0

我正在使用ByteArrayOutputStream将文本从IputStream放入文本视图中。 这工作正常,但... 我来自瑞典,当我把一些文字与一些特殊的瑞典字母,它放?而不是实际的信件。否则,系统对此字母没有问题。 希望有人在那里可以给我一个关于怎么做的提示。在Android中使用ByteArrayOutputStream的瑞典字母问题

也许我应当出示代码:

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 
     } 
    } 
} 
} 
+0

让我们看看你的代码。 –

回答

0

当您读取/写入流时,您正在使用错误的编码。使用UTF-8

outputStream.toString("UTF8") 

编辑:试试这个贴出来的方法here。我认为这也可能是一个问题,如果你的文件有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(); 
} 
+0

对不起,我不知道我在代码中如何使用它。 – Christer

+0

你可以发布你的代码吗? – TheCodeKing

+0

所以最后,将'return byteArrayOutputStream.toString();'改为'return byteArrayOutputStream.toString(“UTF-8”);' – TheCodeKing