How can I read a text file in Android?

前端 未结 7 1538
-上瘾入骨i
-上瘾入骨i 2020-11-22 07:51

I want to read the text from a text file. In the code below, an exception occurs (that means it goes to the catch block). I put the text file in the applicati

7条回答
  •  南旧
    南旧 (楼主)
    2020-11-22 08:46

    If you want to read file from sd card. Then following code might be helpful for you.

     StringBuilder text = new StringBuilder();
        try {
        File sdcard = Environment.getExternalStorageDirectory();
        File file = new File(sdcard,"testFile.txt");
    
            BufferedReader br = new BufferedReader(new FileReader(file));  
            String line;   
            while ((line = br.readLine()) != null) {
                        text.append(line);
                        Log.i("Test", "text : "+text+" : end");
                        text.append('\n');
                        } }
        catch (IOException e) {
            e.printStackTrace();                    
    
        }
        finally{
                br.close();
        }       
        TextView tv = (TextView)findViewById(R.id.amount);  
    
        tv.setText(text.toString()); ////Set the text to text view.
      }
    
        }
    

    If you wan to read file from asset folder then

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

    Or If you wan to read this file from res/raw foldery, where the file will be indexed and is accessible by an id in the R file:

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

    Good example of reading text file from res/raw folder

提交回复
热议问题