I am creating a sample application in my android phone to create a new text file and write some data on to that text file.
Asked
Active
Viewed 1.5k times
0
-
which type of data? – Divyesh Patel Dec 09 '16 at 06:57
-
Same like java. Just you have to mention where to keep that file. e.g. Environment.getExternalStorageDirectory()+"/text/" – Kush Patel Dec 09 '16 at 06:58
-
Normal string data – Gaurav K Dec 09 '16 at 09:52
-
What exactly does Environment.getExternalStorageDirectory() do – Gaurav K Dec 09 '16 at 09:53
1 Answers
9
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" />
for device having os >= LOLIPOP you need to ask permissions runtime, this is the code :
public void generateNoteOnSD(Context context, 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(context, "Saved", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}

Lalit Dhameliya
- 348
- 3
- 8