2011-12-07 33 views
1

我想從放在res/raw /文本中的文本文件中讀取 我已成功讀取,但在輸出中的每一行後都有一個奇怪的字符像這樣的「[]」。 而且這個字符在輸出中每一行的末尾,在我的源文件(文本)中有新行。 不知道如何從每一行中刪除這個角色..未正確讀取Android文本文件(在原始目錄中)

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(); 

}

}

回答

2

您可能正在拾取不需要或未格式化的CR/LF字符,這是將文本分隔到新行的原因。如果您使用的是Windows,則在行末會同時出現CR和LF。在OS X和Linux上,只有一個LF。 (Old Macs只有一個CR)

因此,如果您將文本文件保存在Windows中,並在Android(Linux)上顯示它,則未格式化的文本可能會顯示額外的CR字符,每一行。

要解決它,嘗試從https://stackoverflow.com/a/2549222/324625

+0

感謝stevehb像這樣

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(); } 

部分借用..我已經從你的答案:)解決我的問題 – Itian

0

你是如何創建的文本文件?操作系統處理行尾字符的方式有所不同。 Unix/Linux EOL字符與Windows EOL字符不同,這可以解釋不同之處。