It is easy to read a text file in Android. Let's assume we want to read each line in a text file and be able to access each line as a string in a data structure.
1. First you add the text files you want to the res > raw folder. References to them will be generated in the R.java file.
2. We will define a couple of variables to hold the data to be read. We will create a String to temporary hold each line being read which we will add to a String ArrayList.
3. While you could get the reference IDs to the text files directly from the R.java file, I prefer to use the method getPackageName. This way I am clear which text file I am always using and you don't have to be concerned if the generated ID changes. It also allows run-time user selection of files via file names rather than their generated references.
4. We then setup a BufferedReader with an InputStreamReader, check out the code below:
List<String> list = new ArrayList<String>();
String line;
String fileName="textfile";
int fileID
fileID = res.getIdentifier(fileName, "raw", context.getPackageName());
BufferedReader input = new BufferedReader(
new InputStreamReader(res.openRawResource(fileID)));
while ((line=input.readLine()) != null){
list.add(line);
}
input.close();
The getIdentifier() method of Resources is where you can get the ID to the file by supplying it the file name.Use a Try/Catch block in the event the file is missing.
You now have the data from your text file captured in an ArrayList where each line is one item in the ArrayList.
No comments:
Post a Comment