Android creates folders, generates files, and writes text files.
1. add permissions first
<Uses-permission android: name = "android. permission. WRITE_EXTERNAL_STORAGE"> </uses-permission>
2. Create a folder, generate a file, and write the text file content code
Private void initData (){
String filePath = "/sdcard/Test /";
String fileName = "log.txt ";
WriteTxtToFile ("txt content", filePath, fileName );
}
// Write the string to a text file
Public void writeTxtToFile (String strcontent, String filePath, String fileName ){
// Generate a folder and then generate the file. Otherwise, an error will occur.
MakeFilePath (filePath, fileName );
String strFilePath = filePath + fileName;
// Line feed is written each time it is written.
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 );
}
}
// Generate a file
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;
}
// Generate a 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 + "");
}