Skip to main content

Android: Loading files from the Assets and Raw folders

This post will explain how to load files from the res/raw and the Assets folder using a String to specify the file name. Yes, there are a lot of tutorials on this subject, but they all use the automatically generated integer IDs from the R class as inputs and not many of them even mention the possibility of loading files from the Assets folder. 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 the raw folder and the Assets folder. Since raw is a subfolder of Resources (res), Android will automatically generate an ID for any file located inside it. This ID is then stored an the R class that will 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 generated ID is the fastest way to have access to a file in Android.
The Assets folder is an “appendix” directory. The R class 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 a String. 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 the Assets folder.
Here’s the code:


01. package fortyonepost.com.lfas;
02.
03. import java.io.ByteArrayOutputStream;
04. import java.io.IOException;
05. import java.io.InputStream;
06.
07. import android.app.Activity;
08. import android.content.res.Resources;
09. import android.os.Bundle;
10. import android.util.Log;
11. import android.widget.Toast;
12.
13. public class LoadFromAltLoc extends Activity {
14.
15. //a handle to the application's resources
16. private Resources resources;
17. //a string to output the contents of the files to LogCat
18. private String output;
19.
20. /** Called when the activity is first created. */
21. @Override
22. public void onCreate(Bundle savedInstanceState)
23. {
24. super.onCreate(savedInstanceState);
25. setContentView(R.layout.main);
26.
27. //get the application's resources
28. resources = getResources();
29.
30. try
31. {
32. //Load the file from the raw folder - don't forget to OMIT the extension
33. output = LoadFile("from_raw_folder", true);
34. //output to LogCat
35. Log.i("test", output);
36. }
37. catch (IOException e)
38. {
39. //display an error toast message
40. Toast toast = Toast.makeText(this, "File: not found!", Toast.LENGTH_LONG);
41. toast.show();
42. }
43.
44. try
45. {
46. //Load the file from assets folder - don't forget to INCLUDE the extension
47. output = LoadFile("from_assets_folder.txt", false);
48. //output to LogCat
49. Log.i("test", output);
50. }
51. catch (IOException e)
52. {
53. //display an error toast message
54. Toast toast = Toast.makeText(this, "File: not found!", Toast.LENGTH_LONG);
55. toast.show();
56. }
57. }
58.
59. //load file from apps res/raw folder or Assets folder
60. public String LoadFile(String fileName, boolean loadFromRawFolder) throws IOException
61. {
62.
63. InputStream iS;
64.
65. if (loadFromRawFolder)
66. {
67. //get the resource id from the file name
68. int rID = resources.getIdentifier("fortyonepost.com.lfas:raw/"+fileName, null,
69. //get the file as a stream
70. iS = resources.openRawResource(rID);
71. }
72. else
73. {
74. //get the file as a stream
75. iS = resources.getAssets().open(fileName);
76. }
77.
78. //create a buffer that has the same size as the InputStream
79. byte[] buffer = new byte[iS.available()];
80. //read the text file as a stream, into the buffer
81. iS.read(buffer);
82. //create a output stream to write the buffer into
83. ByteArrayOutputStream oS = new ByteArrayOutputStream();
84. //write this buffer to the output stream
85. oS.write(buffer);
86. //Close the Input and Output streams
87. oS.close();
88. iS.close();
89.
90. //return the output stream as a String
91. return oS.toString();
92. }
93. }



The first thing the code does is to create two private variables. A Resources object that will act as a handle to the app’s resources and a String, 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 the LoadFile() method is defined. It returns a String and takes two parameters: the first one is the file name and the second is a boolean, that signals the method whether it should load from the res/raw or the Assets folder.
After that, the method creates a InputStream object (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 the loadFromRawFolder parameter is true. Case it is, the code at lines 68 and 70  is executed. The former dynamically loads resources from the raw folder. The getIdentifier() method from the resources object returns a resource ID based on the path. This parameter is composed by:
package name:type of resource/file name
Package name is self explanatory; type of resource can be one of the following: raw, drawable, string. File name, in this example, is the fileName parameter, an it’s being concatenated to create one single String. Since all information that this method requires is being passed on the first parameter the other two can be null.
Finally, line 70 feeds this ID to the openRawResource() method, which will return a InputStream from a file located at the res/raw folder.
At the else block, the Assets folder is being opened, by first calling the getAssets() method to return a handle to the Assets folder and right after that, the open() method is called, passing the fileName as the parameter. All that is done to also return the InputStream, although this time, for a file at the Assets folder (line 75).
Now that we have the InputStream, we can create the buffer to read the file into. That’s accomplished by line 79, that creates a byte array that has exactly the same length as iS (the InputStream object). 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 a OutputStream to write the buffer contents into. First, a object of this type is created at line 83. Then, the write() 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 the oS object to a String (line 91).
At last, the LoadFile() 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 a try/catch block since they can throw an exception.
The returned String from the method calls are stored at the output variable. 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 a String. Additionally, it can be used to dynamically to acquire a reference, and load files at run time.
Downloads
loadresourcesaltlocations.zip

Comments

Popular posts from this blog

ESP32-C6 Wi-Fi Logger with Browser GPS + Heat Map Dashboard

This project is an ESP-IDF firmware for the Seeed Studio XIAO ESP32-C6 that turns the board into a self-hosted, secure Wi-Fi scanning logger. It creates its own access point, serves a responsive HTTPS web UI, logs nearby Wi-Fi access points, optionally tags rows with GPS coordinates (provided by the client browser), and exposes battery status from the on-board LiPo input. The end result is a pocket Wi-Fi “survey” tool: scan, track, export logs as CSV, and generate a heat map view to visualize RSSI vs location. Project overview and feature set: :contentReference[oaicite:1]{index=1} What it does AP + Station mode so the device can serve the dashboard while scanning nearby Wi-Fi networks. HTTPS web interface using a bundled certificate/key for local secure access. Single scan and continuous tracking modes. CSV export for analysis and archiving. Persistent logging to SPIFFS at /spiffs/logs.csv . Battery monitoring via ADC with voltage/percentage/status sh...

learn how to sniff wireless passwords with pirni

The thing about the iPod Touch and the iPhone is that they are great portable hacking devices. To the naked eye the iPod Touch/iPhone looks like nothing more than an ordinary mp3 player/cellphone however that is just an understatement to its full potential. Once your Ipod Touch/iPhone is jailbroken you have access to your whole file system meaning that applications generally associated with laptop/desktop hacking can be ported and used on the iPod Touch/iPhone. This opens up a whole lot of possibilities for network sniffing, port scanning and much much more! In this tutorial we are going to take a look at one of these programs called Pirni. What is Pirni? Pirni is an application that was ported to The Ipod Touch/iPhone to be used as a native network sniffer. Pirni is so useful because it gets past the iPod Touch’s/iPhone’s wifi hardware limitation of not being able to be set into promiscious mode (a mode that allows a network device to intercept and read each network packet that arrive...

Performance Monitoring

Performance Monitoring "System Accounting," teaches about the UNIX accounting system, and the tools that the accounting system provides. Some of these utilities and reports give you information about system utilization and performance. Some of these can be used when investigating performance problems. In this portion of the book, you will learn all about performance monitoring. There are a series of commands that enable system administrators, programmers, and users to examine each of the resources that a UNIX system uses. By examining these resources you can determine if the system is operating properly or poorly. More important than the commands themselves, you will also learn strategies and procedures that can be used to search for performance problems. Armed with both the commands and the overall methodologies with which to use them, you will understand the factors that are affecting system performance, and what can be done to optimize them so that the system performs...