Differences between fileoutputstream and openfileoutput () in Android ()

Source: Internet
Author: User
Tags delete cache

From: http://www.cnblogs.com/elleniou/archive/2012/05/17/2505630.html

Openfileoutput ()

First, we will introduce how to store data using files. Activity provides the openfileoutput () method that can be used to output data to files, the specific implementation process is the same as saving data to a file in the j2se environment.

Public void save ()
{
Try {
Fileoutputstream outstream+this.openfileoutput(+a.txt ", context. mode_world_readable );
Outstream. Write (text. gettext (). tostring (). getbytes ());
Outstream. Close ();
Toast. maketext (myactivity. This, "saved", Toast. length_long). Show ();
} Catch (filenotfoundexception e ){
Return;
}
Catch (ioexception e ){
Return;
}
}

 

The first parameter of the openfileoutput () method is used to specify the file name. It cannot contain the path separator "/". If the file does not exist, Android will automatically create it. The created file is saved in the/data/<package name>/Files directory, for example,/data/CN. itcast. action/files/itcast.txt, click "window"-"Show View"-"other" in the eclipse menu, expand the android folder in the dialog box, and select the file explorer view below, expand the/data/<package name>/Files directory in the file explorer view to view the file.
The second parameter of the openfileoutput () method is used to specify the operation mode. There are four modes: context. mode_private = 0
Context. mode_append = 32768
Context. mode_world_readable = 1
Context. mode_world_writeable = 2
Context. mode_private: the default operation mode. This mode indicates that the file is private data and can only be accessed by the application itself. In this mode, the written content will overwrite the content of the original file, if you want to append the newly written content to the original file. You can use context. mode_append.
Context. mode_append: the mode checks whether the file exists and appends the content to the file if it exists. Otherwise, a new file is created.
Context. mode_world_readable and context. mode_world_writeable are used to control whether other applications have the permission to read and write the file.
Mode_world_readable: indicates that the current file can be read by other applications; mode_world_writeable: indicates that the current file can be written by other applications.
If you want the file to be read and written by other applications, you can pass in:
Openfileoutput(“itcast.txt ", context. mode_world_readable + context. mode_world_writeable );

Androidhas a set of security models. When the application program (.apk) is installed, the system will assign a userid to it. When the application wants to access other resources, such as files, it needs to match the userid. By default, files created by any application, sharedpreferences, and databases, should be private (in/data/<package name>/files), and cannot be accessed by other programs. Unless context. mode_world_readable or context. mode_world_writeable is specified during creation, only other programs can access it correctly.
Read File Content

 

Public void load ()
{
Try {
Fileinputstream instream#this.openfileinput()a.txt ");
Bytearrayoutputstream stream = new bytearrayoutputstream ();
Byte [] buffer = new byte [1024];
Int length =-1;
While (length = instream. Read (buffer ))! =-1 ){
Stream. Write (buffer, 0, length );
}
Stream. Close ();
Instream. Close ();
Text. settext (stream. tostring ());
Toast. maketext (myactivity. This, "loaded", Toast. length_long). Show ();
} Catch (filenotfoundexception e ){
E. printstacktrace ();
}
Catch (ioexception e ){
Return;
}
}

 

Only applications that create a private file can access the file. If you want the file to be read and written by other applications, you can specify the context. mode_world_readable and context. mode_world_writeable permissions when creating the file.
Activity also provides the getcachedir () and getfilesdir () methods:
The getcachedir () method is used to obtain the/data/<package name>/cache directory.
The getfilesdir () method is used to obtain the/data/<package name>/Files directory.

  

Put the file into the SD card

 

Use the openfileoutput () method of activity to save files. The files are stored in the mobile phone space. Generally, the mobile phone storage space is not very large, and it is okay to store some small files, it is not feasible to store large files such as videos. For large files like videos, we can store them in sdcard. What does sdcard do? You can think of it as a mobile hard disk or a USB flash disk.

To use sdcard in the simulator, You need to first create an sdcard (of course, not a real sdcard, but an image file ). You can create sdcard along with the simulator created in eclipse, or use the doscommand to create it, as shown below:

Enter the tools directory in the android SDK installation path in the DOS window, and enter the following command to create an sdcard with a capacity of 2 GB. The file suffix can be obtained at will. IMG is recommended:

Mksdcard 2048 m d: \ androidtool \ sdcard. img

To access sdcard in a program, you need to apply for the permission to access sdcard.

The permission to access sdcard in androidmanifest. XML is as follows:

<! -Create and delete file permissions in sdcard->

<Uses-Permission Android: Name = "android. Permission. mount_unmount_filesystems"/>

<! -Write Data to sdcard->

<Uses-Permission Android: Name = "android. Permission. write_external_storage"/>

 

To store files in sdcard, the program must first determine whether the mobile phone is equipped with sdcard and can read and write data.

Note: The permission to access sdcard must be added to androidmanifest. xml.

If (environment. getexternalstoragestate (). Equals (environment. media_mounted )){

File sdcarddir = environment. getexternalstoragedirectory (); // get the sdcard directory

File SaveFile = new file (sdcarddir, cmda.txt ");

Fileoutputstream outstream = new fileoutputstream (SaveFile );

Outstream. Write ("test". getbytes ());

Outstream. Close ();

}

The environment. getexternalstoragestate () method is used to obtain the sdcard status. If the mobile phone has an sdcard and can be read and written, the returned state is environment. media_mounted.

The environment. getexternalstoragedirectory () method is used to obtain the sdcard directory. To obtain the sdcard directory, you can also write:

File sdcarddir = new file ("/sdcard"); // get the sdcard directory

File SaveFile = new file (sdcarddir, “itcast.txt ");

// The code above can be combined into a sentence: file SaveFile = new file ("/sdcard/a.txt ");

Fileoutputstream outstream = new fileoutputstream (SaveFile );

Outstream. Write ("test". getbytes ());

Outstream. Close ();

The following is an example of using openfileoutput to access the object:
Public class mainactivity extends activity {@ override protected void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. activity_main);} public void button (view) {person P = new person (); p. setage (10); p. setname ("Lee"); saveobject (P, "mainactivity. dat ");} public void button2 (view) {person P = (person) readobject (" mainactivity. dat "); system. out. println (P. getage ();} public Boolean saveobject (serializable Ser, string file) {fileoutputstream Fos = NULL; objectoutputstream OOS = NULL; try {Fos = openfileoutput (file, mode_private ); oos = new objectoutputstream (FOS); OOS. writeobject (SER); OOS. flush (); Return true;} catch (exception e) {e. printstacktrace (); Return false;} finally {try {OOS. close () ;}catch (exception e) {}try {FOS. close ();} catch (exception e) {}}/*** read object * @ Param file * @ return * @ throws ioexception */Public serializable readobject (string file) {fileinputstream FCM = NULL; objectinputstream OIS = NULL; try {fiis = openfileinput (File); ois = new objectinputstream (FS); Return (serializable) Ois. readobject ();} catch (filenotfoundexception e) {} catch (exception e) {e. printstacktrace (); // deserialization failed-delete cache file if (E instanceof invalidclassexception) {file data = getfilestreampath (File); data. delete () ;}finally {try {Ois. close () ;}catch (exception e) {}try {FCM. close () ;}catch (exception e) {}} return NULL ;}} class person implements serializable {int age; string name; Public int getage () {return age ;} public void setage (INT age) {This. age = age;} Public String getname () {return name;} public void setname (string name) {This. name = Name ;}}

 

First, we will introduce how to store data using files. Activity provides the openfileoutput () method that can be used to output data to files, the specific implementation process is the same as saving data to a file in the j2se environment.

Public void save ()
{
Try {
Fileoutputstream outstream+this.openfileoutput(+a.txt ", context. mode_world_readable );
Outstream. Write (text. gettext (). tostring (). getbytes ());
Outstream. Close ();
Toast. maketext (myactivity. This, "saved", Toast. length_long). Show ();
} Catch (filenotfoundexception e ){
Return;
}
Catch (ioexception e ){
Return;
}
}

 

The first parameter of the openfileoutput () method is used to specify the file name. It cannot contain the path separator "/". If the file does not exist, Android will automatically create it. The created file is saved in the/data/<package name>/Files directory, for example,/data/CN. itcast. action/files/itcast.txt, click "window"-"Show View"-"other" in the eclipse menu, expand the android folder in the dialog box, and select the file explorer view below, expand the/data/<package name>/Files directory in the file explorer view to view the file.
The second parameter of the openfileoutput () method is used to specify the operation mode. There are four modes: context. mode_private = 0
Context. mode_append = 32768
Context. mode_world_readable = 1
Context. mode_world_writeable = 2
Context. mode_private: the default operation mode. This mode indicates that the file is private data and can only be accessed by the application itself. In this mode, the written content will overwrite the content of the original file, if you want to append the newly written content to the original file. You can use context. mode_append.
Context. mode_append: the mode checks whether the file exists and appends the content to the file if it exists. Otherwise, a new file is created.
Context. mode_world_readable and context. mode_world_writeable are used to control whether other applications have the permission to read and write the file.
Mode_world_readable: indicates that the current file can be read by other applications; mode_world_writeable: indicates that the current file can be written by other applications.
If you want the file to be read and written by other applications, you can pass in:
Openfileoutput(“itcast.txt ", context. mode_world_readable + context. mode_world_writeable );

Androidhas a set of security models. When the application program (.apk) is installed, the system will assign a userid to it. When the application wants to access other resources, such as files, it needs to match the userid. By default, files created by any application, sharedpreferences, and databases, should be private (in/data/<package name>/files), and cannot be accessed by other programs. Unless context. mode_world_readable or context. mode_world_writeable is specified during creation, only other programs can access it correctly.
Read File Content

 

Public void load ()
{
Try {
Fileinputstream instream#this.openfileinput()a.txt ");
Bytearrayoutputstream stream = new bytearrayoutputstream ();
Byte [] buffer = new byte [1024];
Int length =-1;
While (length = instream. Read (buffer ))! =-1 ){
Stream. Write (buffer, 0, length );
}
Stream. Close ();
Instream. Close ();
Text. settext (stream. tostring ());
Toast. maketext (myactivity. This, "loaded", Toast. length_long). Show ();
} Catch (filenotfoundexception e ){
E. printstacktrace ();
}
Catch (ioexception e ){
Return;
}
}

 

Only applications that create a private file can access the file. If you want the file to be read and written by other applications, you can specify the context. mode_world_readable and context. mode_world_writeable permissions when creating the file.
Activity also provides the getcachedir () and getfilesdir () methods:
The getcachedir () method is used to obtain the/data/<package name>/cache directory.
The getfilesdir () method is used to obtain the/data/<package name>/Files directory.

  

Put the file into the SD card

 

Use the openfileoutput () method of activity to save files. The files are stored in the mobile phone space. Generally, the mobile phone storage space is not very large, and it is okay to store some small files, it is not feasible to store large files such as videos. For large files like videos, we can store them in sdcard. What does sdcard do? You can think of it as a mobile hard disk or a USB flash disk.

To use sdcard in the simulator, You need to first create an sdcard (of course, not a real sdcard, but an image file ). You can create sdcard along with the simulator created in eclipse, or use the doscommand to create it, as shown below:

Enter the tools directory in the android SDK installation path in the DOS window, and enter the following command to create an sdcard with a capacity of 2 GB. The file suffix can be obtained at will. IMG is recommended:

Mksdcard 2048 m d: \ androidtool \ sdcard. img

To access sdcard in a program, you need to apply for the permission to access sdcard.

The permission to access sdcard in androidmanifest. XML is as follows:

<! -Create and delete file permissions in sdcard->

<Uses-Permission Android: Name = "android. Permission. mount_unmount_filesystems"/>

<! -Write Data to sdcard->

<Uses-Permission Android: Name = "android. Permission. write_external_storage"/>

 

To store files in sdcard, the program must first determine whether the mobile phone is equipped with sdcard and can read and write data.

Note: The permission to access sdcard must be added to androidmanifest. xml.

If (environment. getexternalstoragestate (). Equals (environment. media_mounted )){

File sdcarddir = environment. getexternalstoragedirectory (); // get the sdcard directory

File SaveFile = new file (sdcarddir, cmda.txt ");

Fileoutputstream outstream = new fileoutputstream (SaveFile );

Outstream. Write ("test". getbytes ());

Outstream. Close ();

}

The environment. getexternalstoragestate () method is used to obtain the sdcard status. If the mobile phone has an sdcard and can be read and written, the returned state is environment. media_mounted.

The environment. getexternalstoragedirectory () method is used to obtain the sdcard directory. To obtain the sdcard directory, you can also write:

File sdcarddir = new file ("/sdcard"); // get the sdcard directory

File SaveFile = new file (sdcarddir, “itcast.txt ");

// The code above can be combined into a sentence: file SaveFile = new file ("/sdcard/a.txt ");

Fileoutputstream outstream = new fileoutputstream (SaveFile );

Outstream. Write ("test". getbytes ());

Outstream. Close ();

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.