Saturday, 6 February 2016

Create text file in android programmatically


Here I am going to explain how to create text file and insert data to that file on android


Step 1)

 private void writeFile(String name)
    {

      try {
      File root = new File(Environment.getExternalStorageDirectory(), "History");
            if (!root .exists()) {
                root .mkdirs();
            }
            File file= new File(root, "example.txt");
            FileWriter writer = new FileWriter(file);
            writer.append(name);
            writer.flush();
            writer.close();
     Toast.makeText(MainActivity.this, "Saved", Toast.LENGTH_SHORT).show();
          
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


Step 2)Adding permissions to Manifest file.

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


HappyCoding:)