Android file read and write examples

Source: Internet
Author: User

1 ImportJava.io.FileInputStream;2 Importjava.io.FileNotFoundException;3 ImportJava.io.FileOutputStream;4 Importjava.io.IOException;5 Importorg.apache.http.util.EncodingUtils;6 7  Public classMylogfile {8       Private StaticFileOutputStream Fout;9        PublicMylogfile () {Ten       }  One  A        Public Static voidCreateFile () { -            Try { -Fout =NewFileOutputStream ("/mnt/sdcard/zyrpad.txt"); the                 //fout = openfileoutput ("/mnt/sdcard/zyrpad.txt", Mode); -}Catch(FileNotFoundException e) { - e.printstacktrace (); -           }  +      }  -  +      //files written under the/mnt/sdcard/directory A       Public Static voidWritefilesdcard (String message) { at            Try{  -                  //FileOutputStream fout = Openfileoutput (FileName, mode_private); -message= message+ "\ n"; -                 byte[] bytes =message.getbytes (); - fout.write (bytes); -}Catch(Exception e) { in e.printstacktrace (); -            } to       } +  -       //read the file below the/mnt/sdcard/directory the        Publicstring Readfilesdcard (String fileName) { *String res= ""; $             Try{ Panax NotoginsengFileInputStream fin =NewFileInputStream (fileName); -                   intLength =fin.available (); the                   byte[] buffer =New byte[length]; + fin.read (buffer); Ares = encodingutils.getstring (buffer, "UTF-8");  the fin.close (); +}Catch(Exception e) { - e.printstacktrace (); $             } $             returnRes; -       }  -  the       /*** Close File stream*/  -        Public Static voidCloseFile () {Wuyi             Try { the fout.close (); -}Catch(IOException e) { Wu e.printstacktrace (); -             } About       }  $}

The call is simple:
Mylogfile.createfile ();//Create File
Mylogfile.writefilesdcard ("------------write text to File----------------");

When you're done, remember to close it:
Mylogfile.closefile ()

Android file read and write examples

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.