Writing a file to sdcard

//------------------------------WRITING DATA TO THE FILE ---------------------------------      

btnWriteSDFile.setOnClickListener(new OnClickListener() 
    {
    public void onClick(View v)
    {       

        try {
            File myFile = new File("/sdcard/mysdfile.txt");
            myFile.createNewFile();
            FileOutputStream fOut = new FileOutputStream(myFile);
            OutputStreamWriter myOutWriter =new OutputStreamWriter(fOut);
            myOutWriter.append(txtData.getText());
            myOutWriter.close();
            fOut.close();
            Toast.makeText(v.getContext(),"Done writing SD 'mysdfile.txt'", Toast.LENGTH_SHORT).show();
            txtData.setText("");
        } 
        catch (Exception e) 
        {
            Toast.makeText(v.getContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
        }
    }


    }); 

//---------------------------READING DATA FROM THE FILE PLACED IN SDCARD-------------------//       
        btnReadSDFile.setOnClickListener(new OnClickListener()
        {

        public void onClick(View v) 
        {

        try {

            File myFile = new File("/sdcard/mysdfile.txt");
            FileInputStream fIn = new FileInputStream(myFile);
            BufferedReader myReader = new BufferedReader(new InputStreamReader(fIn));
            String aDataRow = "";
            String aBuffer = "";
            while ((aDataRow = myReader.readLine()) != null) 
            {
                aBuffer += aDataRow ;
            }
            txtData.setText(aBuffer);
            myReader.close();
            Toast.makeText(v.getContext(),"Done reading SD 'mysdfile.txt'",Toast.LENGTH_SHORT).show();
        } 
        catch (Exception e)
        {
            Toast.makeText(v.getContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
        }
        }
        }); 

ALONG WITH THIS ALSO WRITE THIS PERMISSION IN Android.Manifest

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Leave a Comment