Android file operations

Source: Internet
Author: User
Tags java fileinputstream

Androidthe file OperationOneAndroidIntroduction to File Operations

To understandAndroidof file storage, first understandAndroidhow to get and deposit data in what way. Androidthe file operations are carried out through a stream, i.e.IO. Androidthe file operation withJavais the same, file operations are divided into input streams (InputStream) and the output stream (outputstream), the input stream is used to obtain the file data, and the output stream is used to store the file. Both the input stream and the output stream are memory-intensive, so using theAndroidof theIO, you should always remember to close it after use unless you have special needs.IOChannel. And then we'll explain,InputStream and OutputStream.

1,InputStream

InputStream is an abstract class that represents a superclass of all classes of a byte input stream. Here are some of the methods that InputStream often use.

void

Close ()
closes this input stream and frees all system resources associated with the stream.

abstract int

Read ()
reads the next data byte from the input stream.

Int

Read (byte[] b)
reads a certain number of bytes from the input stream and stores it in an array of buffers b the.

Int

Read (byte[] b, int off, int len)
the maximum number of input streams Len Byte array is read in bytes of data bytes.

Where the Close method requires special attention, remember to call the Close method to close the input stream in a timely manner.

2,OutputStream

OutputStream is an abstract class that represents a superclass of all classes of a byte output stream. Here are some of the methods that outputstream often use.

void

Close ()
closes this output stream and frees all system resources related to this stream.

void

Write (byte[] b)
will be B.length bytes to write to this output stream from a specified byte array.

void

Write (byte[] b, int off, int len)
moves the specified byte array from the offset off started with Len bytes written to this output stream.

abstract void

Write (int b)
writes the specified bytes to this output stream.

As with InputStream, remember to call the close method to close the output stream in a timely manner.

Ii. acquisition and use of InputStream and OutputStream. 1, OperationAndroidof theSDCard's File

For example, in android go to android phone's own memory (not sd card) Read and write files .

Activity context   There are ways to get output and write streams.
are:
Openfileoutput (name, mode);
Openfileinput (name);
Mode there
        context.mode_ Private;  // default, only this program private
         context.mode_append;   // Append method
         context.mode_world_readable;   // (other program) readable
        context.mode_world_writeable;  // (other program) writable

Note: SD card IO requires permissions:
Android.permission.MOUNT_UNMOUNT_FILESYSTEMS
Android.permission.WRITE_EXTERNAL_STORAGE

2, usingFileInputStream Getting files

In 1 we talked about using Openfileoutput (name, mode) and Openfileinput (name) to get the output stream and the data input stream separately, which is provided in the original Java FileInputStream and FileOutputStream classes, respectively, inherit from InputStream and OutputStream, and in Android through this two class can also get input stream and output stream.

1. How to use FileInputStream

Here's how the FileInputStream is constructed

FileInputStream (File file)
by opening a connection to the actual file to create a FileInputStream , the file is passed through the file system File Object file specified.

FileInputStream (FileDescriptor fdobj)
by using the file descriptor Fdobj Create a FileInputStream A file descriptor that represents an existing connection to an actual file in the file system.

FileInputStream (String name)
by opening a connection to the actual file to create a FileInputStream , the file is passed through the path name in the file system name specified.

Corresponding Code:

NewFileName for file address InputStream is= new FileInputStream (NewFileName);

2. How to use FileOutputStream

Here's how the FileOutputStream is constructed

FileOutputStream (File file)
Create a to specify File object represents the file output stream in which the data is written.

FileOutputStream (File File, Boolean append)
Create a to specify File object represents the file output stream in which the data is written.

FileOutputStream (FileDescriptor fdobj)
creates an output file stream that writes data to the specified file descriptor, which represents an existing connection to an actual file in the file system.

FileOutputStream (String name)
creates an output file stream that writes data to a file with the specified name.

FileOutputStream (String name, Boolean append)
creates a direction with the specified name the output file stream that writes the data to the file.

Corresponding Code:

NewFileName for the file address to be generated outputstream OS = new FileOutputStream (newfilename);


Note: also requires permissions :
Android.permission.MOUNT_UNMOUNT_FILESYSTEMS
Android.permission.WRITE_EXTERNAL_STORAGE

3, GetAndroidof theData for the Assets folder

In Android , sometimes you don't just need to get the files in the SD card, just get the files from the assets. That's the way the code can handle it.

InputStream is = Context.getresources (). Getassets (). open (Mfilename);

Third, code example 1. Read file data from resource 's asset

String fileName = "Test.txt"; File name string res= ""; try{    //Get Asset data stream in the resource   inputstream in = Getresources (). Getassets (). open (fileName);    int length = in.available ();           byte [] buffer = new Byte[length];           In.read (buffer);               res = encodingutils.getstring (buffer, "UTF-8");       } catch (Exception e) {       e.printstacktrace ();            }


2.Read and write the files in the SD card. This is the file under the/mnt/sdcard/directory:

Write data to SD file public void Writefilesdcardfile (String filename,string write_str) {try{        fileoutputstream fout = new FileOutputStream (fileName);       byte [] bytes = Write_str.getbytes ();        Fout.write (bytes);       Fout.close ();     }       catch (Exception e) {        e.printstacktrace ();       }   }    Read the file public in SD string Readfilesdcardfile (String fileName) {  string res= "";  try{         fileinputstream fin = new FileInputStream (fileName);          int length = fin.available ();          byte [] buffer = new Byte[length];         Fin.read (buffer);              res = encodingutils.getstring (buffer, "UTF-8");          Fin.close ();            }         catch (Exception e) {         e.printstacktrace ();        }        return res;}


The above section refers to the blog post on the network, with a small demo.

http://download.csdn.net/detail/stop_pig/7896851

Android file operations

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.