When creating an Android application, I have some files that needs to be stored on the android itself.
How do I do this?
When creating an Android application, I have some files that needs to be stored on the android itself.
How do I do this?
If you have local files, like some error tones, some openning video.. then place it in you assets folder of your project
.
If you have dynamic data need to download at run time then use this guide.
Best place for generic files would be the assets
folder.
You can access files through the AssetManager
, which you can get with Activity.getAssets()
for example.
Here is an example how you could access a text file:
try {
BufferedReader br = new BufferedReader(
new InputStreamReader(getAssets().open("sometextfile.txt")));
// do stuff with br
} catch (IOException e) {
e.printStackTrace();
}
For more information on AssetManager
read the Java Doc. Oh and yes, you can create folders in assets.
If you want to keep some files like readme.txt
or even music files, you can use the raw folder inside of res
folder. So create a folder named raw
inside of res
folder.
Inside of raw folder, let us assume that there is a file named readme.txt
, assuming that the Activity class is called MyActivity
.
Now, you can read the contents of a file into a String as shown below:
StringBuilder strContents = new StringBuilder();
String thisLine;
InputStream is = MyActivity.this.getResources().openRawResource(R.raw.readme);
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
while ((thisLine = br.readLine()) != null) { // while loop begins here
strContents.append(thisLine);
}
br.close();
//Now you have the data in strContents
Alternately, assets
is also one such folder that you can use since the raw folder contains the file as is without any optimization, zipping done by Android.
So create an assets
folder in your Project root folder and place your files there e.g. myfile
.
Now, you can get an instance of the file InputStream as given below:
InputStream is = getBaseContext().getAssets().open("mydb");