CREATE AND INSERT DATA TO A TEXT FILE IN ANDROID

Pooja Malohtra

Total Post:47

Points:331
Posted by  Pooja Malohtra
 565  View(s)
Ratings:
Rate this:
I want to create a text file, file.txt and insert data on file with content of some of variable on my code for example : population [][]; on Android, so there will be folder files on our package in file explorer (data/data/ourpackage/files/ourfiles.txt) 
Please suggest me the correct steps to implement this. 
  1. Mayank Tripathi

    Post:397

    Points:3117
    Re: Create and insert data to a text file in android

    Use these code you can write a text file in SDCard along with you need to set permission in android manifest
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    this is the code :

    public void generateNoteOnSD(String sFileName, String sBody){
        try
        {
            File root = new File(Environment.getExternalStorageDirectory(), "Notes");
            if (!root.exists()) {
                root.mkdirs();
            }
            File gpxfile = new File(root, sFileName);
            FileWriter writer = new FileWriter(gpxfile);
            writer.append(sBody);
            writer.flush();
            writer.close();
            Toast.makeText(this, "Saved", Toast.LENGTH_SHORT).show();
        }
        catch(IOException e)
        {
             e.printStackTrace();
             importError = e.getMessage();
             iError();
        }
       }  
    before writing files also check whether your SDCard is Mounted & your external storage state is writable

    Environment.getExternalStorageState()

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!