Question

I have this code for reading a txt.file from assets folder and showing this txt.file in a textview ??

package com.example.text;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import android.app.Activity;
import android.content.Context;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.widget.TextView;

public class Text2 extends Activity {
    private TextView txt;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            setContentView(R.layout.text2);
            txt=(TextView)findViewById(R.id.textView1);        

            AssetManager assetManager = getAssets();
            InputStream inputStream = null;
            try {
                 inputStream = assetManager.open("hi.txt");
                 BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
                 StringBuilder total = new StringBuilder();
                 String line;
                 while ((line = r.readLine()) != null) {
                      total.append(line);
                 }
                 txt.setText(total.toString());
            }
            catch (IOException e){
                 e.printStackTrace();
            }
     }
}

it works very well but I have a problem .... when I type in my notepad for example:

hi everyone

hello

but when I run this code in emulator you see:

hi everyonehello

why ??? I want have first hi everyone and two line later have hello but emulator doesn't do it ......... also in my notepad everything is ok .... I mean in notepad I have:

hi everyone

helllo

not

hi everyonehello

!!!!!!!!!!!!!! what can I do ??????

where is problem ?? I want have in my emulator first "hi everyone" and two line later hello

Was it helpful?

Solution 2

You are only appending the string and not the linefeed. Try modifying your append to:

total.append(line + "\n");

OTHER TIPS

You are using BufferReader readLine method which is not reading \n or \r.

Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed. Returns: A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached

http://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html#readLine().

Suggest you to use simple read method of the same class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top