Home > DeveloperSection > Forums > Create and insert data to a text file in android
Pooja Malohtra
Pooja Malohtra

Total Post:47

Points:331
Posted on    January-11-2016 11:15 PM

 Android Android 
Ratings:


 1 Reply(s)
 283  View(s)
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. 


Mayank Tripathi
Mayank Tripathi

Total Post:397

Points:3117
Supported
Posted on    January-11-2016 11:19 PM

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()

Don't want to miss updates? Please click the below button!

Follow MindStick