【问题标题】:Android Text file(in raw directory) not being read properlyAndroid 文本文件(在原始目录中)未正确读取
【发布时间】:2012-01-15 08:34:56
【问题描述】:

我想从 res/raw/text 中的文本文件中读取 我阅读成功,但在我的输出中的每一行之后都有一个奇怪的字符,比如“[]”。 这个字符位于输出中每一行的末尾,在我的源文件(文本)中有新行的地方。 不知道如何从每一行中删除这个字符..

  public class HelpActivity extends Activity{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.help);
    TextView textview = (TextView)findViewById(R.id.TextView_HelpText);
    textview.setText(readTxt());

}
private String readTxt() {
     InputStream is = getResources().openRawResource(R.raw.text);
        ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
         int i;

        try
        {

            i = is.read();
            while (i != -1)
            {
                byteArray.write(i);
                i = is.read();
            }
            is.close();
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block

            e.printStackTrace();
        }
        return byteArray.toString();

}

}

【问题讨论】:

    标签: android android-layout


    【解决方案1】:

    您是如何创建文本文件的?操作系统处理行尾字符的方式有所不同。 Unix/Linux EOL 字符与 Windows EOL 字符不同,这可以解释差异。

    【讨论】:

      【解决方案2】:

      您可能会拾取不需要的或未格式化的 CR/LF 字符,这是将文本拆分为新行的原因。如果您使用的是 Windows,则行尾将同时出现 CR 和 LF。在 OS X 和 Linux 上,只有一个 LF。 (旧的 Mac 只有一个 CR。)

      因此,如果您将文本文件保存在 Windows 中,并在 Android (Linux) 上显示它,那么未格式化的文本可能会显示额外的 CR 字符,每行末尾一个。

      要修复它,请尝试类似的方法

      private String readTxt() {
          InputStream is = getResources().openRawResource(R.raw.text);
          BufferedReader r = new BufferedReader(new InputStreamReader(is));
          StringBuilder total = new StringBuilder();
          String line;
          while ((line = r.readLine()) != null) {
              total.append(line);
          }
          return total.toString();
      }
      

      部分借用https://stackoverflow.com/a/2549222/324625

      【讨论】:

      • 谢谢 stevehb.. 我已经从你的回答中解决了我的问题 :)
      猜你喜欢
      • 1970-01-01
      • 2011-05-04
      • 1970-01-01
      • 1970-01-01
      • 2021-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多