Android: Loading files from the Assets and Raw folders

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 ?
  1. packagefortyonepost.com.lfas;//CreatedbyDimasTheDriverApr/2011.
  2. importjava.io.ByteArrayOutputStream;
  3. importjava.io.IOException;
  4. importjava.io.InputStream;
  5. importandroid.app.Activity;
  6. importandroid.content.res.Resources;
  7. importandroid.os.Bundle;
  8. importandroid.util.Log;
  9. importandroid.widget.Toast;
  10. publicclassLoadFromAltLocextendsActivity{
  11. //ahandletotheapplication'sresources
  12. privateResourcesresources;
  13. //astringtooutputthecontentsofthefilestoLogCat
  14. privateStringoutput;
  15. /**Calledwhentheactivityisfirstcreated.*/
  16. @Override
  17. publicvoidonCreate(BundlesavedInstanceState)
  18. {
  19. super.onCreate(savedInstanceState);
  20. setContentView(R.layout.main);
  21. //gettheapplication'sresources
  22. resources=getResources();
  23. try
  24. {
  25. //Loadthefilefromtherawfolder-don'tforgettoOMITtheextension
  26. output=LoadFile("from_raw_folder",true);
  27. //outputtoLogCat
  28. Log.i("test",output);
  29. }
  30. catch(IOExceptione)
  31. {
  32. //displayanerrortoastmessage
  33. Toasttoast=Toast.makeText(this,"File:notfound!",Toast.LENGTH_LONG);
  34. toast.show();
  35. }
  36. try
  37. {
  38. //Loadthefilefromassetsfolder-don'tforgettoINCLUDEtheextension
  39. output=LoadFile("from_assets_folder.txt",false);
  40. //outputtoLogCat
  41. Log.i("test",output);
  42. }
  43. catch(IOExceptione)
  44. {
  45. //displayanerrortoastmessage
  46. Toasttoast=Toast.makeText(this,"File:notfound!",Toast.LENGTH_LONG);
  47. toast.show();
  48. }
  49. }
  50. //loadfilefromappsres/rawfolderorAssetsfolder
  51. publicStringLoadFile(StringfileName,booleanloadFromRawFolder)throwsIOException
  52. {
  53. //CreateaInputStreamtoreadthefileinto
  54. InputStreamiS;
  55. if(loadFromRawFolder)
  56. {
  57. //gettheresourceidfromthefilename
  58. intrID=resources.getIdentifier("fortyonepost.com.lfas:raw/"+fileName,null,null);
  59. //getthefileasastream
  60. iS=resources.openRawResource(rID);
  61. }
  62. else
  63. {
  64. //getthefileasastream
  65. iS=resources.getAssets().open(fileName);
  66. }
  67. //createabufferthathasthesamesizeastheInputStream
  68. byte[]buffer=newbyte[iS.available()];
  69. //readthetextfileasastream,intothebuffer
  70. iS.read(buffer);
  71. //createaoutputstreamtowritethebufferinto
  72. ByteArrayOutputStreamoS=newByteArrayOutputStream();
  73. //writethisbuffertotheoutputstream
  74. oS.write(buffer);
  75. //ClosetheInputandOutputstreams
  76. oS.close();
  77. iS.close();
  78. //returntheoutputstreamasaString
  79. returnoS.toString();
  80. }
  81. }

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

更多相关文章

  1. 代码中设置drawableleft
  2. android 3.0 隐藏 系统标题栏
  3. Android开发中activity切换动画的实现
  4. Android(安卓)学习 笔记_05. 文件下载
  5. Android中直播视频技术探究之—摄像头Camera视频源数据采集解析
  6. 技术博客汇总
  7. android 2.3 wifi (一)
  8. AndRoid Notification的清空和修改
  9. Android中的Chronometer

随机推荐

  1. Android(安卓)JobScheduler/JobService
  2. 一行代码实现Android右滑返回
  3. Android(安卓)内存溢出(Out Of Memory)
  4. Android路由跳转-ARouter框架
  5. Android引路蜂地图开发示例:地址查询
  6. Android(安卓)Dialog 设置圆角无效
  7. android之拨打电话时在电话号码前加17951
  8. Android(安卓)资源详解(一) 颜色、字符串、
  9. 浅析Android的RILD服务进程的消息循环
  10. android Service Binder交互通信实例详解