Android creates folders, generates files, and writes text files.

Source: Internet
Author: User

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 + "");
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.