You can use the example from answer . But with some changes:
public void appendLog(String text)
{
File logFile = new File(Environment.DIRECTORY_DOWNLOADS,"log.txt");
if (!logFile.exists())
{
try
{
logFile.createNewFile();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try
{
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.append(text);
buf.newLine();
buf.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Also, do not forget that since we are writing files in the android file system, we need to request permission:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
And also, just for avoid errors, include this:
<application
....
android:requestLegacyExternalStorage="true">
</application>
Finally, if you are running in android version >=6.0, we recommend to request run time permission, because, even if these are accepted from the application settings it will not work.
How to request runtime permission -> https://developer.android.com/training/permissions/requesting
or you can use a library like a dexter
The log.txt is in the download folder of your android device