File storage in Android

Source: Internet
Author: User

Android uses a Linux-based file system. With the concept that everything in Linux is a file, we can create and access private files of programs, you can also access the original and XML files stored in the Resource Directory.

You can also access and save files on external file devices such as the SD card. It allows you to create a private file system that can only be accessed by yourself. The created files are stored in the directory:/data/<package name>/files.

I. Internal file storage:

Based on the reading or writing of internal files, we usually use two functions: openfileinput (string name, mode) and openfileoutput (string name, mode) these two functions open files in the root directory of your program.

You do not need to specify the file path. If you use fileinputstream, fileoutputstream, filereader bufferreader, and filewriter bufferwriter, you must specify the file read/write path.

When using the above two functions, you must grant the corresponding permissions to the parameters. The Android system has the following four file operation modes:

Description

Mode_private private mode, defect mode, the file can only be accessed by the File Creation Program, or programs with the same uid.

Mode_append mode. If the file already exists, add new data at the end of the file.

The global read mode of mode_world_readable allows any program to read private files.

The global write mode of mode_world_writeable allows any program to write data to a private file.

Perform operations on files using filereader and filewriter as follows:

// Create the file private void docreatefile () {// just prepare the file object file = new file ("/mnt/sdcard/readme.txt"); If (file. exists () = false) {// try {file does not exist. createnewfile (); filewriter fw = new filewriter (File); bufferedwriter BW = new bufferedwriter (FW); BW. write ("File Created by Android !!!!!! "); BW. flush (); BW. close (); FW. close ();} catch (ioexception e) {e. printstacktrace () ;}}// read the private void doreadfile () {file = new file ("/mnt/sdcard/readme.txt"); If (file. exists () = true) {// exists! Try {filereader Fr = new filereader (File); bufferedreader BR = new bufferedreader (FR); string strline = BR. readline (); TV. settext (strline); BR. close (); Fr. close ();} catch (filenotfoundexception e) {e. printstacktrace ();} catch (ioexception e) {e. printstacktrace ();}}}
// Use filefilterprivate void dolistfilesversion2 () {file = new file ("/mnt/sdcard"); // The filter filters only files suffixed with .txt, filefilter FF = new filefilter () {@ overridepublic Boolean accept (File file) {If (file. getname (). endswith (". TXT ") {return true;} else {return false ;}}; file [] files = file. listfiles (ff); For (File onfile: Files) {TV. append ("\ n" + onfile. getname ());}}

The following operations are performed on files using the openfileoutput and openfileinput functions:

Case R. id. button2: // write string datastr = tv2.gettext (). tostring (); string file_name = "myfile.txt"; fileoutputstream Fos = NULL; try {Fos = openfileoutput (file_name, // file name context. mode_world_readable + context. mode_world_writeable);} catch (filenotfoundexception e) {// todo auto-generated catch blocke. printstacktrace ();} Try {FOS. write (datastr. getbytes (); FOS. flush (); // write the remaining data to the file FOS. close ();} Ca Tch (ioexception e) {e. printstacktrace ();} break; case R. id. button3: // read fileinputstream FCM = NULL; try {FD = openfileinput ("myfile.txt");} catch (filenotfoundexception e) {// todo auto-generated catch blocke. printstacktrace ();} byte [] buffer = NULL; try {buffer = new byte [Sox. available ()]; while (FCM. read (buffer )! =-1) {} string showstr = new string (buffer); tv2.settext (showstr);} catch (ioexception e) {// todo auto-generated catch blocke. printstacktrace ();} break;

2. External Storage:

The code above should actually be operated on the external file, because you can specify the file path to operate the external file, but note that you must be in androidmanifest. register related read/write permissions in XML

Otherwise, normal read/write operations cannot be performed.

Obtain the path of the photo in the simulator:

Public class mainactivity extends activity {private button select; private final string image_type = "image/*"; private final int image_code = 0; @ override public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. activity_main); select = (button) findviewbyid (R. id. select); select. setonclicklistener (new view. onclicklistener () {public void onclick (V Iew v) {intent getalbum = new intent (intent. action_get_content); getalbum. settype (image_type); startactivityforresult (getalbum, image_code) ;}}) ;}protected void onactivityresult (INT requestcode, int resultcode, intent data) {If (resultcode! = Result_ OK) {// here result_ OK is a constant defined by the system;} bitmap Bm = NULL; contentresolver resolver = getcontentresolver (); If (requestcode = image_code) {try {URI originaluri = data. getdata (); // retrieve the image URI Bm = mediastore. images. media. getbitmap (Resolver, originaluri); // The second part starting from the bitmap image. Obtain the image path: String [] proj = {mediastore. images. media. data}; cursor = managedquery (originaluri, proj, null); // according to my personal understanding, this is the index value of the image selected by the user. Int column_index = cursor. getcolumnindexorthrow (mediastore. images. media. data); cursor. movetofirst (); // obtain the image path string Path = cursor Based on the index value. getstring (column_index); log. E ("lostinai", PATH);} catch (ioexception e) {log. E ("lostinai", E. tostring ());}}}}

Save the image to the SD card:

Public void onclick (view v) {inputstream is = getresources (). openrawresource (IA. imageid (pictureid); file = new file ("/mnt/sdcard/item.png"); If (! File. exists () {try {file. createnewfile (); system. out. println ("File Created successfully");} catch (ioexception e) {system. out. println ("file creation failed") ;}try {try {fileoutputstream Fos = new fileoutputstream (File); byte [] buffer = new byte [is. available ()]; while (is. read (buffer )! =-1) {FOS. write (buffer);} FOS. flush (); FOS. close (); is. close ();} catch (filenotfoundexception e) {system. out. println ("file cannot be found") ;}} catch (ioexception e) {system. out. println ("input/output stream exception ");}}

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.