How to read a selected text file from sdcard on android

后端 未结 3 514
旧巷少年郎
旧巷少年郎 2020-12-06 14:37

i am new at android development and i need your help. I was locking at topics that are similar for my development but non of then help me. So far i create functions that get

3条回答
  •  借酒劲吻你
    2020-12-06 15:13

    I used this code to read a text file in SD card,

    public class ReadFileSDCardActivity extends Activity {  
        /** Called when the activity is first created. */  
        @Override  
        public void onCreate(Bundle savedInstanceState) {  
            super.onCreate(savedInstanceState);  
            setContentView(R.layout.main);  
    
            //Find the view by its id  
            TextView tv = (TextView)findViewById(R.id.fileContent);  
    
            File dir = Environment.getExternalStorageDirectory();  
            //File yourFile = new File(dir, "path/to/the/file/inside/the/sdcard.ext");  
    
            //Get the text file  
            File file = new File(dir,"text.txt");  
            // i have kept text.txt in the sd-card  
    
            if(file.exists())   // check if file exist  
            {  
                  //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  
                }  
                //Set the text  
                tv.setText(text);  
            }  
            else  
            {  
                tv.setText("Sorry file doesn't exist!!");  
            }  
         }  
    }  
    

提交回复
热议问题