Reading a line of a txt file in assets
I have a text file placed in assets and I want to read one line of it at a time. My problem is that I do not know how to access the file in Activity, and then once I access it, how would I go about only selecting one line?
If keeping the txt file in assets is a bad idea, where should I put it for easier a开发者_StackOverflowccess?
I really appreciate any help!
This is a snippet I use to prepopulate tables in my RSS feed reader. You can use it as a track for your needs.
In res/raw/
I have file feeds.txt
. The file is referenced is code like R.raw.feeds
.
final Resources resources = mHelperContext.getResources();
InputStream inputStream = resources.openRawResource(R.raw.feeds);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream), 8192);
try {
String line;
while ((line = reader.readLine()) != null) {
//make the use you want with "line"
}
} catch (IOException e) {
Log.e(TAG, "Error loading sample feeds.");
throw new RuntimeException(e);
}
To open assests, you'll need to call
<context>.getAssets().open(<your file>);
<context>
is your activity, so if this is in your onCreate
, then it would be this
. That call returns an inputstream, which you can then handle however you please.
I don't see how it would be a particularly bad idea to keep your text file there, depends on what you're using that text file for.
Try this:
Make a new method for example readMyFile(). It must looks like this:
private String readMyFile(File file) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(file));
StringBuilder txt = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
txt.append(line);
txt.append("\n");
}
reader.close();
return txt.toString();
Paste it to your code, and use the method (readMyFile([the file what you want to read in assets]).
Hope it helps.
精彩评论