Skip to content

Instantly share code, notes, and snippets.

@mariomartinezsz
Last active December 27, 2015 20:19
Show Gist options
  • Save mariomartinezsz/7383946 to your computer and use it in GitHub Desktop.
Save mariomartinezsz/7383946 to your computer and use it in GitHub Desktop.
Create and write file in Android
private void writeFile(){
String root = Environment.getExternalStorageDirectory().toString();
//String root = Environment.getRootDirectory().toString();
File myDir = new File(root + "/mydir");
myDir.mkdirs();
String fname = "myfile.txt";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
BufferedWriter buf = new BufferedWriter(new FileWriter(file, true));
buf.append("This is the first line of my file.\n");
buf.append("This is the last one.");
buf.newLine();
buf.flush();
buf.close();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, e.toString(),Toast.LENGTH_LONG).show();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment