Android: Loading files from the Assets and Raw folders

Android: Loading files from the Assets and Raw folders_第1张图片

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. Android 10 获取相册图片失败
  2. Android图片旋转实例
  3. Android获取图片Uri/path
  4. 【Android】图片切换组件ImageSwitcher的运用
  5. Android 创建圆形背景图片
  6. Android base64 上传图片
  7. Android显示网络图片相关实现方法浅谈
  8. android 中Drawable跟Bitmap转换及常用于图片相关操作方法 - And
  9. android带图片的AlertDialog和文件管理器(代码)

随机推荐

  1. android WallpaperPicker7.0源码分析
  2. 线程 同步 ConditionVariable
  3. Android(安卓)Theme.AppCompat.Light报错
  4. umeng android 统计类部署
  5. Android(安卓)AsyncLayoutInflater 源码
  6. Android自学之路,主界面的搭建Drawerlayou
  7. Android中关于sdcard的操作
  8. Android(安卓)SurfaceTexture解读
  9. Android异步任务 android-async-http
  10. Linux下android内核编译