First you have to give permission to read and write on your AndroidManifest.xml
. Behold:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Remembering that you should watch and start from Android 6.0 (API level 23), users grant permissions to applications while they are running, not when they are installed. See more details about request for runtime permissions.
This approach optimizes the application installation process, as the
user does not need to grant permissions when installing or updating
application. It also gives the user more control over the
app features.
Hand in the cookie jar
Once this is done, you can create a method by passing the context, the file name and the file contents as a parameter for recording. See how it would look:
public void gerarArquivo(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();
//aqui você exibe na tela uma mensagem que o arquivo foi salvo
Toast.makeText(context, "Saved", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
To read the contents of the file, you can create a method by passing as parameter the name of the file in which its return will be one String
. See how it would look:
public static String lerArquivo(String rFilename) {
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard, rFilename);
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
} catch (IOException e) {
// exibir erro caso não funcione
}
return text.toString();
}
For more details you can read in the documentation about save files internally and externally. If the device does not have an external location to save, the ideal is to put a condition in which it checks and saves the file in the most appropriate location.
References
If u will save key-value pairs because it does not use sharedPreferences?
– leofontes
Why save to txt?
– viana
In reality the values are just an example, I need to save much more information... This text file I need to generate will also be a kind of "Backup of information", because in a later procedure the database will receive a delete, however this text file has to be saved. The text file will also serve as a "log" of the information. As if it were a redundancy of information. If Sqlite fails, it has several reasons...
– fvmoraes