How to create text file and insert data to that file on Android
How can I create 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) Thank You
Solution 1:
Using this code you can write to a text file in the SDCard. Along with it, you need to set a permission in the Android Manifest.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
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();
}
}
Before writing files you must also check whether your SDCard is mounted & the external storage state is writable.
Environment.getExternalStorageState()
Solution 2:
Check the android documentation. It's in fact not much different than standard java io file handling so you could also check that documentation.
An example from the android documentation:
String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();