The difference analysis between FileOutputStream and Openfileoutput () in Android programming _android

Source: Internet
Author: User
Tags file permissions

This paper analyzes the difference between FileOutputStream and Openfileoutput () in Android programming. Share to everyone for your reference, specific as follows:

Openfileoutput ()

First of all to introduce how to use files to store data, activity provides a openfileoutput () method can be used to output data to a file, the specific implementation process and in the J2SE environment to save data to the file is the same.

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 specifies the file name, cannot contain the path delimiter "/", and if the file does not exist, Android automatically creates it. The files created are saved in the/data/data/<package Name>/files directory, such as:/data/data/cn.itcast.action/files/itcast.txt, by clicking on the Eclipse menu " Window '-Show View-' other ', expand the Android folder in the Conversation window, select the File Explorer view below, and then expand/data/data/<package in the File Explorer view The file is visible to the Name>/files directory.

The second parameter of the Openfileoutput () method is used to specify the mode of operation, with four modes, respectively: context.mode_private = 0
Context.mode_append = 32768
context.mode_world_readable = 1
Context.mode_world_writeable = 2
Context.mode_private: For the default mode of operation, the file is private data and can only be accessed by the application itself, in which the written content overwrites the contents of the original file, if you want to append the newly written content to the original file. You can use the Context.mode_append
Context.mode_append: Mode checks whether the file exists, appends to the file, or creates a new file.
Context.mode_world_readable and context.mode_world_writeable are used to control whether other applications have permission to read and write to the file.
Mode_world_readable: Indicates that the current file can be read by another application; Mode_world_writeable: Indicates that the current file can be written by another application.
If you want the file to be read and written by another application, you can pass in:

Copy Code code as follows:
Openfileoutput ("Itcast.txt", context.mode_world_readable + context.mode_world_writeable);

Android has its own security model, and when the application (. apk) is installed, the system assigns him a userid, and when the application accesses other resources such as files, it needs userid matching. By default, any file created by the application, sharedpreferences, should be private (located in/data/data/<package name>/files) and not accessible by other programs. Unless context.mode_world_readable or context.mode_world_writeable are specified at the time of creation, only such other programs can access them correctly.

Read File contents

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
    ;
  }
}

For private files that can only be accessed by the application that created the file, if you want the file to be read and written by another application, you can specify context.mode_world_readable and Context.mode_world_writeable permissions when you create the file.

The activity also provides Getcachedir () and Getfilesdir () methods:
The Getcachedir () method is used to get the/data/data/<package Name>/cache directory
The Getfilesdir () method is used to get the/data/data/<package name>/files directory

Put the file into the SD card

Use the activity of the Openfileoutput () method to save the file, the file is stored in the mobile phone space, the general mobile phone storage space is not very large, storing small files also line, if you want to store such large files as video, it is not feasible. For large files like video, we can store them in SDcard. What's sdcard for? You can think of it as a removable hard disk or a USB drive.

To use SDcard in the emulator, you need to create a SDcard card (not really sdcard, just a mirrored file). Creating SDcard can be created when eclipse creates the emulator, or it can be created using a DOS command, as follows:

In the DOS window into the Android SDK installation path of the tools directory, enter the following command to create a capacity of 2G sdcard, file suffix can be arbitrarily taken, recommended. IMG:

Mksdcard 2048M D:\AndroidTool\sdcard.img

To access the SDcard in your program, you need to apply for access to SDcard permissions.

The right to join the access SDcard in Androidmanifest.xml is as follows:

<!– Create and delete file permissions in SDcard –>
<uses-permission android:name= "Android.permission.MOUNT_UNMOUNT_FILESYSTEMS "/>
<!– writes data permissions to SDcard –>
<uses-permission android:name=" android.permission.WRITE_EXTERNAL_ STORAGE "/>

To store files to SDcard, the program must first determine whether the phone is fitted with sdcard and can read and write.

Note : access to SDcard must be included in Androidmanifest.xml to access SDcard permissions

if (Environment.getexternalstoragestate (). Equals (environment.media_mounted)) {
   File Sdcarddir = Environment.getexternalstoragedirectory ()//Get SDcard directory
   file SaveFile = new file (Sdcarddir, "a.txt");
   FileOutputStream OutStream = new FileOutputStream (savefile);
   Outstream.write ("Test". GetBytes ());
   Outstream.close ();
}

The Environment.getexternalstoragestate () method is used to obtain the state of the sdcard, and if the phone has sdcard and can read and write, the state of the method return equals Environment.media_ Mounted.

Environment.getexternalstoragedirectory () method is used to get the directory of SDcard, of course, to obtain the SDcard directory, you can also write:

File Sdcarddir = new file ("/sdcard"); Gets the SDcard directory
file SaveFile = new file (Sdcarddir, "itcast.txt"); 
The above two code can synthesize one sentence: file SaveFile = new file ("/sdcard/a.txt");
FileOutputStream OutStream = new FileOutputStream (savefile);
Outstream.write ("Test". GetBytes ());
Outstream.close ();

Finally attach an example 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);
    The public void button (view view) {Person p = new person ();
    P.setage (10);
    P.setname ("Lee");
  Saveobject (P, "MainActivity.dat");
    public void Button2 (view 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 ();
 The catch (Exception e) {}}}/**  * Read Object * @param file * @return * @throws ioexception/public Serializable readobject (String file) {F
    Ileinputstream FIS = null;
    ObjectInputStream ois = null;
      try{FIS = openfileinput (file);
      OIS = new ObjectInputStream (FIS);
    Return (Serializable) ois.readobject ();
      }catch (FileNotFoundException e) {}catch (Exception e) {e.printstacktrace ();
        Deserialization failed-Deletion of cache file if (e instanceof invalidclassexception) {File data = Getfilestreampath (file);
      Data.delete ();
      }}finally{try {ois.close ();
      catch (Exception e) {} try {fis.close ();
  The catch (Exception e) {}} return null;
  The class person is 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;

 }
}

For more information on Android-related content readers can view the site topics: "Android Development Introduction and Advanced Course", "Android Database Operating skills summary" and "Android Control usage Summary"

I hope this article will help you with the Android program.

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.