First you have to give read and write permission on your AndroidManifest.xml
. See:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Remembering that you should observe and start from Android 6.0 (API level 23), users grant permissions to applications while they are running, not when they are installed. See Requesting Runtime Permissions for more details.
This approach streamlines the application installation process as the
user does not need to grant permissions when installing or updating the
app. It also gives the user more control over the
application features.
Hand in hand
Once you have done this, you can create a method by passing the context, the file name, and the contents of the file to the recording. Here's 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 the file name in which its return will be String
. Here's 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 the documentation on saving files internally and externally . If the device does not have an external location to save, it is best to place a condition in which it checks and saves the file to the most appropriate location.
References