Search code examples
javabufferedreader

Read int from file separated by comma


I have this code here, that reads numbers from a file and stores them in a String array.

        public static void main(String [] args) throws Exception{


             BufferedReader br = new BufferedReader(new FileReader("/Users/Tda/desktop/ReadFiles/scores.txt"));

             String line = null;

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

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

               for(String str : values){
               System.out.println(str);
               }

              }

             System.out.println("");

             br.close();            

         }

But if I wanted to store the values from the String array in a int array, how should I do?

The file that I'm reading looks something like this.

      23,64,73,26
      75,34,21,43

Solution

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

    // new int[] with "values"'s length
    int[] intValues = new int[values.length];
    // looping over String values
    for (int i = 0; i < values.length; i++) {
        // trying to parse String value as int
        try {
            // worked, assigning to respective int[] array position
            intValues[i] = Integer.parseInt(values[i]);
        }
        // didn't work, moving over next String value
        // at that position int will have default value 0
        catch (NumberFormatException nfe) {
            continue;
        }
    }
    

    ... and to test:

    System.out.println(Arrays.toString(intValues));