Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create text file and insert data to that file on Android

Tags:

file

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

like image 332
Michelle Avatar asked Nov 16 '11 13:11

Michelle


People also ask

How do you create a data txt file?

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 .

How do I create a text file in File Manager?

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.


2 Answers

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() 
like image 73
Karthi Avatar answered Sep 21 '22 07:09

Karthi


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(); 
like image 38
hcpl Avatar answered Sep 24 '22 07:09

hcpl