Search code examples
androidfilefilereaderphone-numberstringbuffer

How to Read from text file and Store into an Array in android


Hie Friends

I am developing an android application in that text file should be generated with some numbers. and after this one by one application should call to that numbers.

For eg:

9876452125, 9876452135, 9876452115,

Mostly that text file have 8 numbers which is Separated by "," and New Line "\n"

Now I want to read From that file line by line.

My Code for read file and store to array is:

public void read(String fname)
    {
        BufferedReader br = null;
        try
        {
            StringBuffer output = new StringBuffer();
            String fpath = "/sdcard/" + fname + ".txt";
            br = new BufferedReader(new FileReader(fpath));
            String line = null;
            int index = 0;

            String[][] num = new String[15][10];

            List<String[]> collection = new ArrayList<String[]>();
            while ((line = br.readLine()) != null)
            {
                if (index < num.length)
                {

                    output.append(line);
                    // output.append("\n");

                    num[index] = line.split(",");

                    if (num.length > 0)
                    {
                        collection.add(num[index]);
                    }
                }
                Toast.makeText(getApplicationContext(), "" + collection, 5000)
                        .show();
                index++;

            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

Now My problem is when I printing collection to Toast it display some random strings. I don't know why??

Does any one have proper idea or sample code for how to read from file line by line and store to Array.

Thanks allot.


Solution

  •    ArrayList<ArrayList<String>> myArray = new ArrayList<ArrayList<String>>();
    
        ArrayList<String> stringArray = new ArrayList<String>();
        String random = "9876452125, 9876452135, 9876452115,";
    
        String[] splitArray = random.split(",");
    
        for (int i = 0; i < splitArray.length; i++) {
    
            stringArray.add(splitArray[i]);
        }
    
        myArray.add(stringArray);
    
        // printing all values
        for (int i = 0; i < myArray.size(); i++) {
            for (int j = 0; j < myArray.get(i).size(); j++) {
    
                System.out.println("values of index " + i + " are :"
                        + myArray.get(i).get(j));
            }
        }