Android: Loading files from the Assets and Raw folders
Android: Loading files from the Assets and Raw folders
Posted by DimasTheDriver | Filed underProgramming
This tutorial will explain how to load files from theres/rawand theAssetsfolder using aStringto specify the file name. Yes, there are a lot of tutorials on this subject, but they all use the automatically generatedintegerIDs from theRclass as inputs and not many of them even mention the possibility of loading files from theAssetsfolder. As a result of depending on the ID, the file reference must be known beforehand.
Instead, the code featured in this post will explain how to find the reference to the file and then load it at runtime based solely on its name. This means that the reference ID and the file don’t even have to exist in the first place, and can be acquired at run time.
Before looking into the code, it’s important to highlight the main differences between therawfolder and theAssetsfolder. Sincerawis a subfolder ofResources(res), Android will automatically generate an ID for any file located inside it. This ID is then stored an theRclass thatwill act as a reference to a file, meaning it can be easily accessed from other Android classes and methods and even in Android XML files. Using the automatically generatedIDis the fastest way to have access to a file in Android.
TheAssetsfolder is an “appendix” directory. TheRclass does not generate IDs for the files placed there, so its less compatible with some Android classes and methods. Also, it’s much slower to access a file inside it, since you will need to get a handle to it based on aString. There is also a 1MB size limit for files placed there, however some operations are more easily done by placing files in this folder, like copying a database file to the system’s memory. There’s no (easy) way to create an Android XML reference to files inside theAssetsfolder.
Here’s the code:
view plain copy to clipboard print ?- packagefortyonepost.com.lfas;//CreatedbyDimasTheDriverApr/2011.
- importjava.io.ByteArrayOutputStream;
- importjava.io.IOException;
- importjava.io.InputStream;
- importandroid.app.Activity;
- importandroid.content.res.Resources;
- importandroid.os.Bundle;
- importandroid.util.Log;
- importandroid.widget.Toast;
- publicclassLoadFromAltLocextendsActivity{
- //ahandletotheapplication'sresources
- privateResourcesresources;
- //astringtooutputthecontentsofthefilestoLogCat
- privateStringoutput;
- /**Calledwhentheactivityisfirstcreated.*/
- @Override
- publicvoidonCreate(BundlesavedInstanceState)
- {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- //gettheapplication'sresources
- resources=getResources();
- try
- {
- //Loadthefilefromtherawfolder-don'tforgettoOMITtheextension
- output=LoadFile("from_raw_folder",true);
- //outputtoLogCat
- Log.i("test",output);
- }
- catch(IOExceptione)
- {
- //displayanerrortoastmessage
- Toasttoast=Toast.makeText(this,"File:notfound!",Toast.LENGTH_LONG);
- toast.show();
- }
- try
- {
- //Loadthefilefromassetsfolder-don'tforgettoINCLUDEtheextension
- output=LoadFile("from_assets_folder.txt",false);
- //outputtoLogCat
- Log.i("test",output);
- }
- catch(IOExceptione)
- {
- //displayanerrortoastmessage
- Toasttoast=Toast.makeText(this,"File:notfound!",Toast.LENGTH_LONG);
- toast.show();
- }
- }
- //loadfilefromappsres/rawfolderorAssetsfolder
- publicStringLoadFile(StringfileName,booleanloadFromRawFolder)throwsIOException
- {
- //CreateaInputStreamtoreadthefileinto
- InputStreamiS;
- if(loadFromRawFolder)
- {
- //gettheresourceidfromthefilename
- intrID=resources.getIdentifier("fortyonepost.com.lfas:raw/"+fileName,null,null);
- //getthefileasastream
- iS=resources.openRawResource(rID);
- }
- else
- {
- //getthefileasastream
- iS=resources.getAssets().open(fileName);
- }
- //createabufferthathasthesamesizeastheInputStream
- byte[]buffer=newbyte[iS.available()];
- //readthetextfileasastream,intothebuffer
- iS.read(buffer);
- //createaoutputstreamtowritethebufferinto
- ByteArrayOutputStreamoS=newByteArrayOutputStream();
- //writethisbuffertotheoutputstream
- oS.write(buffer);
- //ClosetheInputandOutputstreams
- oS.close();
- iS.close();
- //returntheoutputstreamasaString
- returnoS.toString();
- }
- }
The first thing the code does is to create two private variables. AResourcesobject that will act as a handle to the app’s resources and aString, that will be used to output the content of the files to LogCat (lines 16 and 18).
Now let’s jump straight to line 60 where theLoadFile()method is defined. It returns aStringand takes two parameters: the first one is the file name and the second is aboolean, that signals the method whether it should load from theres/rawor theAssetsfolder.
After that, the method creates aInputStreamobject (line 63). Streams are like handles to read files into buffers (Input Stream) and to write files from these buffers (Output stream).
Line 65 checks if theloadFromRawFolderparameter is true. Case it is, the code at lines 68 and 70 is executed. The former dynamically loads resources from therawfolder. The getIdentifier() method from theresourcesobject returns a resourceIDbased on the path. This parameter is composed by:
package name:type of resource/file name
Package nameis self explanatory;type of resourcecan be one of the following:raw,drawable,string.File name, in this example, is thefileNameparameter, an it’s being concatenated to create one singleString. Since all information that this method requires is being passed on the first parameter the other two can benull.
Finally, line 70 feeds this ID to theopenRawResource()method, which will return aInputStreamfrom a file located at theres/rawfolder.
At theelseblock, theAssetsfolder is being opened, by first calling thegetAssets()method to return a handle to theAssetsfolder and right after that, theopen()method is called, passing thefileNameas the parameter. All that is done to also return theInputStream, although this time, for a file at theAssetsfolder (line 75).
Now that we have theInputStream, we can create the buffer to read the file into. That’s accomplished by line 79, that creates abytearray that has exactly the same length asiS(theInputStreamobject). The file is read into the buffer at the next line (line 81).
With the file loaded into the buffer, it’s time to prepare aOutputStreamto write the buffer contents into. First, a object of this type is created at line 83. Then, thewrite()method is called passing the buffer as the parameter (line 85). With that, a handle to the file’s content was created.
There’s nothing left to do with these two streams, so they are closed at lines 87 and 88. Finally, the return for this method is set, by converting theoSobject to aString(line 91).
At last, theLoadFile()method is called at line 33 (don’t forget to omit the file extension) and at line 47 (don’t forget to include the file extension). Both method calls are surrounded by atry/catchblock since they can throw an exception.
The returnedStringfrom the method calls are stored at theoutputvariable. It’s then later used to print the contents of the loaded files into LogCat’s console (lines 35 and 49).
And that’s about it! The method that was declared in the Activity can be easily adapted to load and return anything from these folders, not just aString. Additionally, it can be used to dynamically to acquire a reference, and load files at run time.
Downloads
- loadresourcesaltlocations.zip
更多相关文章
- 代码中设置drawableleft
- android 3.0 隐藏 系统标题栏
- Android开发中activity切换动画的实现
- Android(安卓)学习 笔记_05. 文件下载
- Android中直播视频技术探究之—摄像头Camera视频源数据采集解析
- 技术博客汇总
- android 2.3 wifi (一)
- AndRoid Notification的清空和修改
- Android中的Chronometer