Java – Parses single-line values from text files in Android

Parses single-line values from text files in Android… here is a solution to the problem.

Parses single-line values from text files in Android

Is it possible to parse a text file containing one line of values in Android? An example of a file I would like to parse could be:

100,102,106,109,110

The solution I’m looking for is similar to

Log.d(TAG, "value 1" + theFirstValue);    
Log.d(TAG, "value 2" + theSecondValue);

etc...

Any suggestions? Thanks!

Solution

You can use the String.split() method.

File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard, "path/to/the/file");
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {       
    String[] split = line.split(","); 
    for(int i = 0; i < split.length; i++) {
      Log.d(TAG, "value " + i + ": " + split[i]);
    }
}
br.close();

Related Problems and Solutions