How can I read a text file in Android?

前端 未结 7 1529
-上瘾入骨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条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 08:43

    Try this :

    I assume your text file is on sd card

        //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.toString());
    

    following links can also help you :

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

    How to read text file in Android?

    Android read text raw resource file

提交回复
热议问题