Tuesday, 28 February 2012

Write into or create Text File on android internal or External Storage


try {
if (writeFile("sdcard/strs.txt", "My string runs here"))
Log.i("WriteFil", "Success");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


Here the method:



/**
* This method to create text file or append to a text file
*
* @param fullFileLocationBathWithNameAndExten
* like "sdcard/strs.txt"
* @param text
* : the text which will be written in the file
* @return: sucess if the process finished successfully
* @throws IOException
* : error in creating the file
*/
public boolean writeFile(String fullFileLocationBathWithNameAndExten,
String text) throws IOException {
File file = new File(fullFileLocationBathWithNameAndExten);
if (!file.exists()) {

file.createNewFile();

}

// BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(file, true));
buf.append(text);
buf.newLine();
buf.close();

return true;

}

No comments:

Post a Comment