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
The easiest way to create a text file in Windows is to open up the Notepad software program on your computer. The Notepad is a text editor included with Microsoft Windows. A text file is considered a plaintext file and Notepad is only capable of creating and editing plaintext files. Notepad saves any text file with a .
Click on File Manager in the left panel. Select the directory for the new folder, then New and New File. Name the new file and choose the extension type you want. Your new file is now visible.
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()
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With