First, add a permission
<uses-permission android:name= "Android.permission.WRITE_EXTERNAL_STORAGE" ></uses-permission>
Ii. Create a folder, generate a file, and write a text file content code
private void InitData () {
String FilePath = "/sdcard/test/";
String fileName = "Log.txt";
Writetxttofile ("txt content", FilePath, FileName);
}
Writing a string to a text file
public void Writetxttofile (string strcontent, String FilePath, String fileName) {
Create a folder, then generate the file, or you will get an error
Makefilepath (FilePath, fileName);
String strFilePath = filepath+filename;
Write on each write with a newline
String strcontent = strcontent + "\ r \ n";
try {
File File = new file (strFilePath);
if (!file.exists ()) {
LOG.D ("Testfile", "Create the file:" + strFilePath);
File.getparentfile (). Mkdirs ();
File.createnewfile ();
}
Randomaccessfile RAF = new Randomaccessfile (file, "RWD");
Raf.seek (File.length ());
Raf.write (Strcontent.getbytes ());
Raf.close ();
} catch (Exception e) {
LOG.E ("Testfile", "Error on Write File:" + e);
}
}
Generating files
Public File Makefilepath (string filePath, String fileName) {
File file = null;
Makerootdirectory (FilePath);
try {
File = new File (FilePath + fileName);
if (!file.exists ()) {
File.createnewfile ();
}
} catch (Exception e) {
E.printstacktrace ();
}
return file;
}
Build folder
public static void Makerootdirectory (String filePath) {
File file = null;
try {
File = new file (FilePath);
if (!file.exists ()) {
File.mkdir ();
}
} catch (Exception e) {
LOG.I ("Error:", e+ "");
}
Android Create folders, generate files and write content to text files