How can I read a text file from the SD card in Android?

后端 未结 6 2247
太阳男子
太阳男子 2020-11-22 16:42

I am new to Android development.

I need to read a text file from the SD card and display that text file. Is there any way to view a text file directly in Android or

6条回答
  •  庸人自扰
    2020-11-22 16:53

    In your layout you'll need something to display the text. A TextView is the obvious choice. So you'll have something like this:

    
    

    And your code will look like this:

    //Find the directory for the SD Card using the API
    //*Don't* hardcode "/sdcard"
    File sdcard = Environment.getExternalStorageDirectory();
    
    //Get the text file
    File file = new File(sdcard,"file.txt");
    
    //Read text from file
    StringBuilder text = new StringBuilder();
    
    try {
        BufferedReader br = new BufferedReader(new FileReader(file));
        String line;
    
        while ((line = br.readLine()) != null) {
            text.append(line);
            text.append('\n');
        }
        br.close();
    }
    catch (IOException e) {
        //You'll need to add proper error handling here
    }
    
    //Find the view by its id
    TextView tv = (TextView)findViewById(R.id.text_view);
    
    //Set the text
    tv.setText(text);
    

    This could go in the onCreate() method of your Activity, or somewhere else depending on just what it is you want to do.

提交回复
热议问题