Android reads the content in the Assets folder, androidassets
Android reads the content in the Assets folder
The assets folder is a directory in the android program that stores the relevant external files. Android officially provides the corresponding method to access the content in this folder, therefore, we do not need to perform Code operations such as relevant path judgment. We can directly call relevant methods to open the file and get an InputStream ); then, the byte is read and decoded as the character input stream (InputStreamReader) through the corresponding character encoding method ); then, read text from the character input stream through BufferReader and store the characters in the buffer to provide efficient reading of characters, arrays, and line segments. Finally, we can read the file content row by row.
MainActivity. java
public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); try { InputStream inputStream = getResources().getAssets().open("info.txt"); InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8"); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String info = ""; while ((info = bufferedReader.readLine()) != null) { Log.i("fff", info); Toast.makeText(MainActivity.this, info, 1000).show(); } } catch (IOException e) { e.printStackTrace(); } }}
How does android obtain the file size in the assets folder?
InputStream in = getResources (). getAssets (). open (fileName );
// Obtain the object Byte Count
Int lenght = in. available ();
Android lists folders in assets.
Assume that the files in the asserts directory are as follows.
Traverse the directory in the book and the file name in it in onCreate.
@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); AssetManager asserter = getAssets (); String [] bookDirs = null; try {// and other directories must have files to be listed. BookDirs = asserter. list ("book"); for (String dir: bookDirs) {// obtain the Log in the directory 0, 1. e ("book", dir); String [] books = asserter. list ("book/" + dir); for (String book: books) {// obtain the file Log in the directory. e ("txt", book); InputStream is = asserter. open ("book/" + dir + "/" + book); InputStreamReader isReader = new InputStreamReader (is, "UTF-8"); BufferedReader br = new BufferedReader (isReader ); string line = null; while (( Line = br. readLine ())! = Null) {// read the Log in the txt file. e ("txt content", line);} br. close (); isReader. close () ;}} catch (IOException e) {e. printStackTrace () ;}} output: