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 回答