I'm working on a sort of a magazine app which contains a lot of txt files which I read the text from (only read not write) , And I'm a little bit confused , I have read the documentation about file storage but still don't seem to get the right way to store my txt files. Should those files be in the the Assets? Is it possible to have a folders inside the assets? And if yes how can I acsses these folders?
Asked
Active
Viewed 60 times
1 Answers
0
res/raw will be a good place to put them. If you placed a text file named "article.txt" in the raw resource folder, you would start by putting the file into an InputStream like this (note that "ctx" is a Context which an Activity inherits from):
InputStream inputStream = ctx.getResources().openRawResource(R.raw.article);
Then you turn the InputStream into a String. This can be done about 1000 different ways. Here's one way:
InputStreamReader inputreader = new InputStreamReader(inputStream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
StringBuilder text = new StringBuilder();
try {
while (( line = buffreader.readLine()) != null) {
text.append(line);
text.append('\n');
}
} catch (IOException e) {
return null;
}
String fileContentsStr = text.toString();
Here is a fully working method (using the above conversion technique) to turn a text file from the raw folder into a string. Which I got from this post Android read text raw resource file.
public static String readRawTextFile(Context ctx, int resId)
{
InputStream inputStream = ctx.getResources().openRawResource(resId);
InputStreamReader inputreader = new InputStreamReader(inputStream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
StringBuilder text = new StringBuilder();
try {
while (( line = buffreader.readLine()) != null) {
text.append(line);
text.append('\n');
}
} catch (IOException e) {
return null;
}
return text.toString();
}
Using "article.txt" still, you would call this method from an Activity like so:
readRawTextFile(this, R.raw.article);
-
thank you for your answer , what is the difference between the raw folder and the assets folder? is it possible to add a folder hierarchy to them? – james Sep 23 '14 at 18:40
-
This article should help introduce you to the project structure for Android projects https://developer.android.com/tools/projects/index.html. It is not possible to add subfolders to any res folder, this includes value, drawable, raw, and the others. You can however add subfolders in assets. The answer I provided is for raw resource files, but there are ways to read in .txt files from the assets folder and assets subfolders as well. – Eric Sep 23 '14 at 18:46
-
yes i know thank you , the problem is not about reading it's about what is better for many txt files? raw? assets? doesn't matter? – james Sep 23 '14 at 18:53
-
Whichever is going to be easier for you. I'd say if you have like 10-20+, use assets and group them into subfolders. – Eric Sep 23 '14 at 19:26