Itian
Itian

Reputation: 35

Android Text file(in raw directory) not being read properly

I want to read from the text file which is placed in res/raw/text i am successful in reading but after every line in my output there is a strange character something like this "[]". And this character is at the end of every line in output where there is new line in my source file(text). Don't know how to remove this character from every line..

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

}

}

Upvotes: 1

Views: 557

Answers (2)

Steve Blackwell
Steve Blackwell

Reputation: 5924

You're probably picking up unwanted or unformatted CR/LF characters, which is what splits text to a new line. If you're on Windows, there will be both a CR and LF at the end of the line. On OS X and Linux, there's just a LF. (Old Macs had just a CR.)

So, if you saved your text file in Windows, and are displaying it on Android (Linux), then unformated text might be showing the extra CR characters, one at the end of each line.

To fix it, try something like this

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

Borrowed in part from https://stackoverflow.com/a/2549222/324625

Upvotes: 2

Anasthase
Anasthase

Reputation: 491

How did you create the text file? There is difference on how OS handle end-of-line characters. Unix/Linux EOL character is different from Windows EOL character, this may explain the difference.

Upvotes: 0

Related Questions