How to write text file in SDCARD in Android



Here is the full Source code for write file:

public class MainActivity extends Activity {
private String stringFile;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
stringFile="This is the test string file";
writeFile(stringFile);

}

private void writeFile(String stringFile2) {
try {
            File myFile = new File("/sdcard/testWriteFile.txt");
            myFile.createNewFile();
            FileOutputStream fOut = new FileOutputStream(myFile);
            OutputStreamWriter myOutWriter = 
                                    new OutputStreamWriter(fOut);
            myOutWriter.append(stringFile2);
            myOutWriter.close();
            fOut.close();
            Toast.makeText(getBaseContext(),
                    "Done writing SD 'mysdfile.txt'",
                    Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Toast.makeText(getBaseContext(), e.getMessage(),
                    Toast.LENGTH_SHORT).show();
        }

}

}

Finally you don't forget to declared permission in your androidmanifest.xml file.
----------------

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


Output looks like this:



How to write text file in SDCARD in Android How to write text file in SDCARD in Android Reviewed by D Kshetri on 1:01 AM Rating: 5

No comments:

Powered by Blogger.