Java Read Files From a Different Folder
Android: Loading files from the Avails and Raw folders
Posted past Dimitri | May 24th, 2011 | Filed under Programming
This tutorial will explain how to load files from the res/raw and the Avails folder using a Cord to specify the file proper noun. Yes, in that location are a lot of tutorials on this field of study, merely they all use the automatically generated integer IDs from the R course as inputs and not many of them even mention the possibility of loading files from the Avails folder. Every bit a result of depending on the ID, the file reference must exist known beforehand.
Instead, the code featured in this mail volition explain how to find the reference to the file and then load it at runtime based solely on its proper name. This means that the reference ID and the file don't even take to exist in the first place, and can exist acquired at run time.
Before looking into the lawmaking, it's important to highlight the master differences between the raw binder and the Avails folder. Since raw is a subfolder of Resources (res), Android will automatically generate an ID for whatsoever file located within it. This ID is then stored an the R class that will act as a reference to a file, significant information technology tin can exist easily accessed from other Android classes and methods and fifty-fifty 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 course does not generate IDs for the files placed at that place, and so its less compatible with some Android classes and methods. Also, information technology'due south much slower to access a file inside information technology, since you will need to get a handle to information technology based on a String. There is as well a 1MB size limit for files placed inside the Assets folder, however some operations are more easily done by placing files in this folder, similar copying a database file to the system's memory. In that location'southward no (piece of cake) way to create an Android XML reference to files inside the Assets folder.
Hither's the code:
package fortyonepost.com.lfas;//Created past DimasTheDriver April/2011. import coffee.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import android.app.Activity; import android.content.res.Resource; import android.os.Packet; import android.util.Log; import android.widget.Toast; public class LoadFromAltLoc extends Activity { //a handle to the application'due south resources individual Resources resources; //a string to output the contents of the files to LogCat private Cord output; /** Called when the action is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.principal); //become the application's resource resources = getResources(); try { //Load the file from the raw folder - don't forget to OMIT the extension output = LoadFile("from_raw_folder", truthful); //output to LogCat Log.i("test", output); } catch (IOException east) { //display an error toast message Toast toast = Toast.makeText(this, "File: not found!", Toast.LENGTH_LONG); toast.testify(); } endeavour { //Load the file from assets folder - don't forget to INCLUDE the extension output = LoadFile("from_assets_folder.txt", false); //output to LogCat Log.i("examination", output); } grab (IOException e) { //display an error toast message Toast toast = Toast.makeText(this, "File: not found!", Toast.LENGTH_LONG); toast.testify(); } } //load file from apps res/raw folder or Assets folder public String LoadFile(String fileName, boolean loadFromRawFolder) throws IOException { //Create a InputStream to read the file into InputStream iS; if (loadFromRawFolder) { //become the resource id from the file proper noun int rID = resource.getIdentifier("fortyonepost.com.lfas:raw/"+fileName, nil, null); //get the file as a stream iS = resource.openRawResource(rID); } else { //get the file as a stream iS = resource.getAssets().open(fileName); } //create a buffer that has the same size as the InputStream byte[] buffer = new byte[iS.bachelor()]; //read the text file as a stream, into the buffer iS.read(buffer); //create a output stream to write the buffer into ByteArrayOutputStream bone = new ByteArrayOutputStream(); //write this buffer to the output stream bone.write(buffer); //Close the Input and Output streams oS.close(); iS.close(); //return the output stream as a Cord render oS.toString(); } } The first thing the code does is to create two individual variables. A Resources object that will human action every bit a handle to the app's resource and a String, that volition be used to output the content of the files to LogCat (lines 16 and 18).
At present let'due south 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 proper name and the second is a boolean, that signals the method whether it should load from the res/raw or the Assets binder.
Afterwards 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 lxx is executed. The old dynamically loads resources from the raw folder. The getIdentifier() method from the resource 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 beingness concatenated to create one single String. Since all information that this method requires is existence passed on the first parameter the other two can exist nothing.
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 cake, the Avails binder is being opened, by first calling the getAssets() method to return a handle to the Assets folder and right subsequently that, the open() method is called, passing the fileName as the parameter. All that is done to also return the InputStream, although this fourth dimension, for a file at the Assets binder (line 75).
Now that we accept the InputStream, we tin can create the buffer to read the file into. That's accomplished by line 79, that creates a byte assortment that has exactly the aforementioned length as iS (the InputStream object). The file is read into the buffer at the side by side line (line 81).
With the file loaded into the buffer, information technology's time to prepare a OutputStream to write the buffer contents into. Starting time, a object of this type is created at line 83. So, the write() method is called passing the buffer as the parameter (line 85). With that, a handle to the file's content was created.
At that place'southward nothing left to exercise with these ii streams, then 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 past a try/catch block since they can throw an exception.
The returned String from the method calls are stored at the output variable. It'southward then later used to print the contents of the loaded files into LogCat's panel (lines 35 and 49).
And that'southward about information technology! The method that was declared in the Activity can exist easily adapted to load and return annihilation from these folders, not just a Cord. Additionally, it can exist used to dynamically to acquire a reference, and load files at run time.
Downloads
- loadresourcesaltlocations.zip
montfordhismandent1980.blogspot.com
Source: http://www.41post.com/3985/programming/android-loading-files-from-the-assets-and-raw-folders
0 Response to "Java Read Files From a Different Folder"
Post a Comment