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

Introduction to Kotlin: A Versatile and Modern Programming Language

Kotlin, a versatile and modern programming language, offers developers a concise, safe, and interoperable coding experience. With features like null safety, extension functions, and coroutines, Kotlin enhances productivity and readability, making it an attractive choice for Android development and beyond. Whether you’re new to programming or an experienced developer, exploring Kotlin opens up a world of possibilities for building robust and expressive applications.

Mastering the Android Activity Lifecycle: A Comprehensive Guide

The Android Activity Lifecycle is a fundamental concept for Android developers. It defines how an Activity behaves during its lifecycle, from creation to destruction. Understanding the Activity Lifecycle is crucial for managing resources efficiently and delivering a smooth user experience. In this blog post, we’ll briefly introduce the different states an Activity can be in and the main callback methods associated with each state. Let’s dive in and explore this important aspect of Android app development!

Table of Contents

Send Us A Message