TheJadav

How to append or write data into text file in android?

Here is demo for creating text file and append text to that file in JAVA. For this in Android you have to ask for WRITE_EXTERNAL_STORAGE permission.

you can check this :

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    if (ContextCompat.checkSelfPermission(getBaseContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, WRITE_STORAGE_INT);
        return;
    }
}
Please handle this request in onRequestPermissionsResult.
 
Finally actual code to write text file in java is : 
try{ 
   FileWriter fileWriter = new FileWriter(Environment.getExternalStorageDirectory().getPath() + "/Android/data/com.StampWallet/" + "SBLog.txt", true); 
   fileWriter.write("Hello");
   fileWrite.close(); 
}catch(IOException e){ 
}
 
If you want to write new line in file then use this :  




if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
    fileWriter.write(System.lineSeparator());
} else {
    fileWriter.write(System.getProperty("line.separator"));
}
 




Thanks.

Share this content:

Share:

More Posts

How does data persistence work in Android?

Data persistence in Android is the ability to save data to the device so that it can be accessed later, even if the app is closed or the device is restarted. There are several ways to achieve data persistence in Android

Fragments and Activities: Two Pillars of Android Development

Fragments and Activities are both important components of Android development. Fragments are a good choice for creating reusable and dynamic UIs, while Activities are a good choice for managing the lifecycle of an app’s UI and implementing core features.

Table of Contents

Send Us A Message