3

I am trying to read values of my country array string which reads csv file.

InputStreamReader reader = new InputStreamReader(asset_stream);  
br = new BufferedReader(reader);
String[] country = null;
String cvsSplitBy = ";";

try {
    while ((line = br.readLine()) != null) {
        country = line.split(cvsSplitBy);

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

My code is currently storing the values inside the country variable. But when my loop finishes, I only have the last value read in the loop. How can I store all the values so I can print them after finishing the loop?

2
  • 1
    Can you use a List? Please post some sample data and expected output. Commented Feb 3, 2014 at 15:45
  • In your data, where are the countries: 1. in a column in every line or 2. all in a single line? If 1, then you must first get the column in every line. If 2, in which line are they and why to read all lines? Commented Feb 3, 2014 at 15:52

5 Answers 5

7

Consider using a list to hold the values:

List<String[]> countries = new ArrayList<>();

try {
    while ((line = br.readLine()) != null) {
        countries.add(line.split(cvsSplitBy));    
    }
}

Later you can iterate over this list:

for (String[] country : countries) {
  System.out.println(Arrays.toString(country); // or whatever
}
Sign up to request clarification or add additional context in comments.

2 Comments

thanks a lot @Dunkun. that was quite quick and accurate reply . Works like charm..
@muktoshuvro Then you should select his answer as a solution to your question. Although you could also pick mine ;)
4

Assuming you're reading multiple countries per line, you may be able to use something like this -

public static List<String> getCountryList(InputStream asset_stream) {
    InputStreamReader reader = new InputStreamReader(asset_stream);
    BufferedReader br = new BufferedReader(reader);
    String[] country = null;
    List<String> al = new ArrayList<String>();
    try {
        String line;
        while ((line = br.readLine()) != null) {
            country = line.split(cvsSplitBy);
            for (String s : country) {
                al.add(s);
            }
        }
    } catch (NumberFormatException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        br.close();
    }
    return al;
}

Comments

3

With every loop your are splitting the current line and saving its parts in the country array. Therefore you can only see the results of your last line after the while loop.

If you want to store the splitted results of every line you should use a collection of String[]. For example like this:

LinkedList<String[]> list = new LinkedList<String[]>();
while ((line = br.readLine()) != null) {
    list.add(line.split(cvsSplitBy));
}
//To read values
for (String[] entry : list) {
    //do something with entry
}

3 Comments

Why a LinkedList out of interest?
Since we fill the List line by line and do not know how many elements will be added I expect LinkedList to be better suited than ArrayList (where the backing array has to be copied several times during the creation of the list). Of course it strongly depends on the later use of the List. Btw: I like how you used the List interface in the declaration in your answer, but again this can be a pain for the later use of the variable.
Good point regarding the unknown input size. I probably use ArrayList too often without considering exactly why. After reading your comment, I found this SO question which summarises things nicely.
3

You can store them in one of the collection types. (see http://docs.oracle.com/javase/7/docs/api/java/util/Collection.html)

Java collections provide you various data structures to store and retrieve data in a particular order. For example, a List will allow you to retrieve the data by index and will preserve the insertion order (FIFO). Other data structures like trees, queues, stacks, sets have other properties.

Using a List in your code:

    InputStreamReader reader = new InputStreamReader(asset_stream);  
    br = new BufferedReader(reader);
    List <String[]> countries=new LinkedList <String[]>();

    try {
        while ((line = br.readLine()) != null) {
            countries.add(line.split(cvsSplitBy));
        }
    } catch (NumberFormatException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    for(String[] country: countries)
    {
      //Do something useful with your List
      System.Out.println(country[0]);
    }

3 Comments

why don't you use generics? Everytime you don't use generics a Coffee plant dies.
I HAVE used generics. SO is thinking it is a markup tag... Need to figure out how to escape it
ah ok. sry about that then :).
1

split returns a String-array which you assign to your array country. You should assign the result of split to a position in country, i.e. country[i]. If you do not use a List instead of your array, then you must dimensionate the array first! I.e. create it with a given size new String[size]

4 Comments

@Duncan String[] country = new String[number_of_countries]; Arrays must have a lenght when created.
Ok, gotcha. Not sure that's a real word, but I like it nonetheless :-)
You're right: it is not a real english word. I meant creating an array with a given length.
You should of course use List. But you were asking why you only get the last value in your array?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.