Android Create folders, generate files and write content to text files

Source: Internet
Author: User

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

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.