How to write files in Android?

To write files in Android follow the following steps:

  • Create a variable path with the help of Environment class provided by Android OS
  • Create an object of File which indicates the directory, and pass the path string created earlier. Then use mkdir() method to create the directory.
  • Create a string of file name.
  • Create an object of File with indicates the file, and pass the file name string created earlier. 
  • Check if the file exists. If not then use createNewFile() method to create the file.
  • Create an object of FileWriter with the help of file object created earlier.
  • Create an object of BufferedWriter with the help of fileWriter object created earlier.Create the string that you want to write on the file.
  • Use write() method of the BufferedWriter object.
  • Don't forget to close the object of BufferedWriter and FileWriter in this order.
e.g.
 BufferedWriter output;
FileWriter filewriter;
String strTileText = "";

String directoryName = "programming.notes";
directoryName = directoryName.replace(".", "");

String path = Environment.getExternalStorageDirectory() + "/" + directoryName + "/";

File directory = new File(path);
directory.mkdir();

String fullName = path + "notes.txt";
File file = new File(fullName);
if(!file.exists())
{
file.createNewFile();
}

filewriter = new FileWriter(file, true);
output = new BufferedWriter(filewriter);

strTileText += "Hello World"+ "\n";

output.write(strTileText);
output.close();
filewriter.close();
Android Logo

Comments

Popular posts from this blog

SSLSocketFactory in Android

Architecture Components in Android

DataBinding in Android