I want to create a text file, 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)
Please suggest me the correct steps to implement this.
Aryan Kumar
27-Jun-2023Sure, here is how to create and insert data to a text file in Android:
import android.content.Context; import android.os.Environment; import java.io.File; import java.io.FileOutputStream;
public class MainActivity extends AppCompatActivity {
Code snippet
}
In this code, we first get the directory where the text file will be saved. Then, we create the text file. Finally, we get a FileOutputStream to write to the text file. We write some data to the text file and then close the FileOutputStream.
Here is an explanation of the code:
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)method returns a File object that represents the directory where the text file will be saved.new File(directory, "my_file.txt")creates a File object that represents the text file.new FileOutputStream(file)creates a FileOutputStream object that can be used to write to the text file.write("Hello, world!".getBytes())method writes the string "Hello, world!" to the text file.close()method closes the FileOutputStream.Anonymous User
11-Jan-2016public void generateNoteOnSD(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(this, "Saved", Toast.LENGTH_SHORT).show();
}
catch(IOException e)
{
e.printStackTrace();
importError = e.getMessage();
iError();
}
}