Android: reading files under assets directory (1)

In Android development, resource files are generally divided into two types:

1. The resource file that can be compiled is placed in res directory, such as layout file. This resource file system will automatically generate the ID of the resource file in R.java, which can be accessed directly through R.X.ID.
2. Keep the original file format of the native resource file and store it in the assets directory. Through the AssetManager provided for us by Android system, these resource files are opened and read in the form of simple byte stream. For example, company profile, service agreement, etc. are usually placed in this folder.

First of all, read the txt file in the assets directory. The example code is as follows:

package com.li.readassetfile;

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

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

public class ReadTxtActivity extends Activity {

    private TextView tvContent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_read_txt);

        tvContent = (TextView) findViewById(R.id.tvContent);

        new ReadTxtTask().execute();
    }

    private class ReadTxtTask extends AsyncTask<Void, Void, String> {

        @Override
        protected String doInBackground(Void... params) {
            AssetManager manager = getResources().getAssets();
            try {
                InputStream inputStream = manager.open("joke.txt");
                InputStreamReader isr = new InputStreamReader(inputStream,
                        "UTF-8");
                BufferedReader br = new BufferedReader(isr);
                StringBuilder sb = new StringBuilder();
                String length;
                while ((length = br.readLine()) != null) {
                    sb.append(length + "\n");
                }
                //Shut off flow
                br.close();
                isr.close();
                inputStream.close();

                return sb.toString();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return "";
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            tvContent.setText(result);
        }
    }
}

design sketch:

Don't forget to close the relevant IO stream.
In addition, if the content of the file is long, it may cause ANR, so AsyncTask is used here to read the file.

Keywords: Android Java

Added by aaadispatch on Sun, 03 May 2020 00:02:26 +0300