Search code examples
javaarrayssplitbufferedreader

Read file and store values into two arrays, one for each line


I got this code here:

   try{

        FileReader file = new FileReader("/Users/Tda/desktop/ReadFiles/tentares.txt");

        BufferedReader br = new BufferedReader(file);


        String line = null;


        while((line = br.readLine()) != null){


            String[] values = line.split(",");

            grp1 = new int[values.length]; 


            for(int i=0; i<grp1.length; i++){
                try {
                    grp1[i]= Integer.parseInt(values[i]);

                }catch (NumberFormatException e) {
                    continue;
                }
            }               
            System.out.println(Arrays.toString(grp1));

        }

        System.out.println("");

        br.close();

    }catch(IOException e){
        System.out.println(e);
    }

This is what the file im reading contains.

       grp1:80,82,91,100,76,65,85,88,97,55,69,88,75,97,81 
       grp2:72,89,86,85,99,47,79,88,100,76,83,94,84,82,93

Right now im storing the values into one int array. But if i wanted to store each line of values into two arrays?

Thought about using Arrays.CopyOfRange somehow, and copy the values from the int array into two new arrays.


Solution

  • Before the while

    List<int[]> groups = new ArrayList<>();
    

    Before the end of the loop:

    groups.add(grp1);
    

    Afterwards:

    for (int[] grp : groups) {
        ...
    }
    

    A List is useful for a growing "array".

    groups.size()     grp1.length
    groups.get(3)     grp1[3]
    groups.set(3, x)  grp1[3 = x