Reading a txt file and outputing as a TextView in Android

强颜欢笑 提交于 2019-12-04 18:15:54
Naruto Uzumaki

If you want to keep a .txt file in your Project, you must locate it in the assets folder.
Then you can access it with AssetManger .
Read this topic on how to create your assets folder, and then use this code:

public class subActivity extends Activity {

private TextView textView;
private StringBuilder text = new StringBuilder();

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.text);
    BufferedReader reader = null;

    try {
        reader = new BufferedReader(
            new InputStreamReader(getAssets().open("inputNews.txt")));

        // do reading, usually loop until end of file reading  
        String mLine;
        while ((mLine = reader.readLine()) != null) {
            text.append(mLine);
            text.append('\n');
        }
    } catch (IOException e) {
        Toast.makeText(getApplicationContext(),"Error reading file!",Toast.LENGTH_LONG).show();
        e.printStackTrace();
    } finally {
        if (reader != null) {
        try {
            reader.close();
        } catch (IOException e) {
            //log the exception
        }
    }

    TextView output= (TextView) findViewById(R.id.summtext);
    output.setText((CharSequence) text);

 }
}

As far as I know you cannot read file from so called development folder. But you can move the same file to assets folder in development folder and read from there. ie.

try {
BufferedReader reader = new BufferedReader(
    new InputStreamReader(getAssets().open("inputNews.txt")));

StringBuilder text = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
         text.append(line);
         text.append('\n');
}   
} catch (IOException e) {
    Toast.makeText(getApplicationContext(),"Error reading file!",Toast.LENGTH_LONG).show();
    e.printStackTrace();
}

I hope it helps

You should store those files in assets or raw directory.

And after that you can get inputstream from those files by using ,

If using assets

AssetManager am = context.getAssets();
InputStream is = am.open("test.txt");

OR if you use raw directory then ,

InputStream is = getResources().openRawResource(R.raw.test);

This is the Kotlin version of the answer from above:

var text = ""
var reader: BufferedReader? = null

try {
    reader = BufferedReader(InputStreamReader(assets.open("inputNews.txt")))
    text = reader.readLines().joinToString("\n")
} catch (e: IOException) {
    Toast.makeText(applicationContext, "Error reading license file!", Toast.LENGTH_SHORT).show()
    e.printStackTrace()
} finally {
    try {
        reader?.close()
    } catch (e: IOException) {
        //log the exception
        e.printStackTrace()
    }
    textView.text = text
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!