Read raw resources in Android

Source: Internet
Author: User

Files stored in RES/RAW are not compiled by the platform, but are used as available raw resources.

It is very easy to read original resources.

First, call context. getresource to obtain the resources reference of the current application context.

Call openrawresource (int id) to obtain inputstream.

Finally, operate inputstream to get data.
Note: Put the file in the Res/raw directory, the R class will automatically provide this ID.
Speed-up File Reading
The principle is to read some data in the file to the buffer. The advantage is that if the read content is already in the buffer, the buffered data is read.

If no, the buffer reads data from the file first and then the data is read from the buffer. This reduces the number of file operations to improve performance.

The disadvantage is that extra memory is used as the buffer.

The sample code is as follows:
Inputstream is = resources. openrawresource (R. Raw. hubin );

Bufferedinputstream Buf = new bufferedinputstream (is );
Example 1:

Void readrawfile ()

{

String content;

Resources resources = This. getresources ();

Inputstream is = NULL;

Try {
Is = resources. openrawresource (R. Raw. hubin );

Byte buffer [] = new byte [is. Available ()];

Is. Read (buffer );

Content = new string (buffer );

Log. I (TAG, "read:" + content );

}

Catch (ioexception E)

{

Log. E (TAG, "Write File", e );

}

Finally

{

If (is! = NULL)

{

Try {

Is. Close ();

} Catch (ioexception E)

{

Log. E (TAG, "Close file", e );

}

}

}

}

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.