Parse Android resource files and their reading methods

Source: Internet
Author: User

In Android development, Sam can process resource files in two ways. One is to place all resource files and JNI programs in a separate resource package. When they are used, they are read using files. Alternatively, you can directly use the C ++ Layer Code to read data. Second, add the resource file to the APK. Use different methods to get the content.
Method 1: It is suitable for porting large C ++ programs. Because of the large number of C ++ code, it is unlikely to be changed to JAVA code. Therefore, it is a good way to store them and resource files in a certain way and make them claim to be a system. However, the software must be released in APK + resource package mode.
Method 2: This method is suitable for scenarios where the amount of code is not very large and the number of resources is not very large. After installing the APK, you do not need to copy the resource package. Convenient release.
This article mainly introduces the second method: adding resources to the APK method.
0. Android resource introduction:
During Android Application Development, you usually use the following resources:
Res/drawable: generally used to store image resources. Such as logo.
Res/layout: layout file.
Res/values: stores strings, such as program names.
However, Android can also use other types of resources. Three types are introduced today:
Res/xml: stores xml files. Similar to the aforementioned resources, the resource files stored in the files are compiled into binary data and stored in the installation package. Read xml files using the R class.
Res/raw: stores files. Files in this directory are not compiled as binary files, but stored as files. Read through the R class.
Assets: You can create sub-directories and store different files here. Instead of being compiled into binary, it is stored in directories/files. Read by file name.
1. Various types of file reading:
December 1.1: res/raw:
Android. app. Activity has an indirect parent class: android. content. Context
It has a great relationship with the application resource package:
Public abstract Resources getResources ()
It returns the resource package instance of the application. This instance is an android. content. res. Resources class object.
Sam first adds the raw directory. Select res. From the menu: File-> New-> Folder. Enter the directory name: raw.
Copy A wav---tennis_room.wav file to this directory and Refresh the project.
Check R class in gen.
You have already added the following information: Copy codeThe Code is as follows: public static final class raw {
Public static final int tennis_room = 0x7f040000;
}

Example:Copy codeThe Code is as follows: int byteread = 0;
Byte [] buf = new byte [1, 4096];
FileInputStream inStream = null;

Res = getResources ();
AssetFileDescriptor fd = res. openRawResourceFd (R. raw. tennis_room );

Try {
InStream = fd. createInputStream ();
} Catch (IOException e ){
// TODO Auto-generated catch block
Log. e ("3 DiJoy", "createInputStream error ");
E. printStackTrace ();
}

Try {
While (byteread = inStream. read (buf ))! =-1)
{
// Do something
}
} Catch (IOException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}

1.2: res/xml:
Similar to raw, but related to xml. Next.
GetXml (int id)
1.3: assets:
Similarly, the indirect parent class of android. app. Activity: android. content. Context
There is a method: public abstract AssetManager getAssets ()
Returns the AssetManager instance of the application package.
Use InputStream open (String fileName );
Returns an InputStream.
Then the file can be read.
Note that the file is in the assets root directory.Copy codeThe Code is as follows: AssetManager am = getAssets ();

Try {
Am. open ("a.txt ");
} Catch (IOException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}

The maximum number of assets files is as follows:
UNCOMPRESS_DATA_MAX: 1048567 bytes
Assets file directory analysis:
Use getAssets () to obtain the AssetsManager instance. You can open a file to list all files and directories. But what is its path and directory? Perform the following tests:
First, we program to list all the files and directories under the given directory:Copy codeThe Code is as follows: public void ListAssetsFile (String AssetsPath)
{
AssetManager am = getAssets ();
Try {
String [] FileOrDirName = am. list (AssetsPath );
Log. e ("3 DiJoy", String. format ("In Assets Path: [% s]. there is: [% d] file or Dir ", AssetsPath, FileOrDirName. length ));
For (int I = 0; I <FileOrDirName. length; I ++)
{
Log. e ("3 DiJoy", String. format ("File Or Dir: [% s]", FileOrDirName [I]);
}
} Catch (IOException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}

Return;
}

Focus 1:
How to determine whether a node in Assets is a file or a directory:
When Sam saw some friends on the network, he tried to determine whether there was ".." in the file name. He thought this method was not particularly effective, so he made another attempt.Copy codeThe Code is as follows: // true: Dir. false: file
Public boolean isAssetsDirs (String fileOrDirName)
{
AssetManager am = getAssets ();

Try {
Am. open (fileOrDirName );
Return false;
}
Catch (FileNotFoundException e)
{
Return true;
}
Catch (IOException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
Return true;
}

// Return! (FileName. startsWith (".") | (fileName. lastIndexOf (".")! =-1 ));
}

When am. open () is used, if a directory is specified, a FileNotFoundException exception is thrown. Sam uses this to determine whether a directory is used.
Focus 2:
How to copy a directory under Assets to a local directory:
This is similar:Copy codeThe Code is as follows: # cp DIR_A/*-rf/data /.../
Public boolean CopyAssetsPath (String AssetsPath, String ObjectPath)
{
File ObjPath = new File (ObjectPath );
If (! ObjPath. exists () |! ObjPath. isDirectory ())
{
Log. e ("3 DiJoy", "Object Path not found or not Dir:" + ObjectPath );
Return false;
}

AssetManager am = getAssets ();

Try {
String [] FileOrDirName = am. list (AssetsPath );
// Log. e ("3 DiJoy", String. format ("In Assets Path: [% s]. there is: [% d] file or Dir ", AssetsPath, FileOrDirName. length ));
For (int I = 0; I <FileOrDirName. length; I ++)
{
// If this is a DIR
If (isAssetsDirs (AssetsPath + "/" + FileOrDirName [I])
{
File N_DIR = new File (ObjectPath + "/" + FileOrDirName [I]);
If (! N_DIR.exists ())
{
Log. e ("3 DiJoy", String. format ("Will Create Dir: [% s]", ObjectPath + "/" + FileOrDirName [I]);
N_DIR.mkdir ();
CopyAssetsPath (AssetsPath + "/" + FileOrDirName [I], ObjectPath + "/" + FileOrDirName [I]);
}
}
Else // if this is file. Then copy it
{
Log. e ("3 DiJoy", String. format ("Will Create file: [% s]", ObjectPath + "/" + FileOrDirName [I]);
CopyAssets (AssetsPath + "/" + FileOrDirName [I], ObjectPath + "/" + FileOrDirName [I]);
}
// Log. e ("3 DiJoy", String. format ("File Or Dir: [% s]", FileOrDirName [I]);
}
} Catch (IOException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}

Return true;
}

The program is simple:
Use list to list all files and directories.
For Directory: create a directory with the same name in the target region.
If it is a file, copy it.
Focus 3:
How to access and copy a file larger than 1 MB:
In the above program, if the number of files exceeds 1 MB, an exception is reported.
The exception that throws java. io. IOException is as follows:
DEBUG/asset (1123): Data exceeds UNCOMPRESS_DATA_MAX (xxxxxxxx vs 1048576 );
Note: The following files are not limited to 1 MB.Copy codeThe Code is as follows: jpg ",". jpeg ",". png ",". gif ",". wav ",". mp2 ",". mp3 ",". ogg ",". aac ",". mpg ",". mpeg ",". mid ",". midi ",". smf ",". jet ",". rtttl ",". imy ",". xmf ",". mp4 ",". m4a ",". m4v ",". 3gp ",". 3gpp ",". 3g2 ",". 3gpp2 ",". amr ",". awb ",". wma ",". wmv"

You can add the following file name to a file that exceeds the size.
Test 1:
Test root directory location:
ListAssetsFile ("/");
The information is as follows:
The directory is actually the root directory after APK decompression:
The content includes:
AndroidManifest. xm.
Assets
META-INFO
Lib
Res
Classes. dex
Resources. arsc
Test 2:
Test relative path location:
ListAssetsFile ("");
The list content is in the Assets Directory. But somehow, three items are added:
Image, sound, webkit.
Test 3: test the current path:
ListAssetsFile ("./");
In theory, the./directory should be the same as the current directory. For some reason, no file can be obtained here. I don't quite understand.
Due to test 3, I have doubts about whether the Android Assets Directory is the same as the concept in Linux. Therefore, I will test again:
Test 4:
Check whether the absolute path is available:
ListAssetsFile ("/assets ");
Haha, it confirmed that it could not get any of the files.
Test 4:
Check whether files other than assets can be accessed using an absolute path:
ListAssetsFile ("/lib ");
0 files are returned. Haha.
Conclusion:
To access the assets file, you can only use the relative path ./

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.