read data from a file in java

后端 未结 5 1196
被撕碎了的回忆
被撕碎了的回忆 2021-01-17 04:32

I have a text file in the following format:

Details.txt

The file is a .txt file. I want to read course title from this file and print corresponding textbook

5条回答
  •  忘掉有多难
    2021-01-17 05:23

    //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');
        }
    }
    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);
    

提交回复
热议问题