Search code examples
javafile-iobufferedreader

Best way to read integers from a text file into an array


Assume i have a text file like this.

1 4 6
2 3    
5 8 9 4
2 1
1

What i want to do is to store them into a 2d array exactly how they are represented. After some googling and reading i came up with the following code.

Scanner s = new Scanner(new BufferedReader(new FileReader("myData.txt")));     

while (s.hasNextLine())
{
    String myStr = s.nextLine();
    x = 0;
    for ( int y = 0; y <= myStr.length(); y+=2)
    {
        myStr = myStr.trim();
        tempStr = myStr.substring(y, y+1)
        num[row][coln] = Integer.parseInt(tempStr);
        coln++
    }
    row++;
}

It works okay, but for integers that have only 1 digit. But what if i have integers of different length. How can i do it to dynamically check length of integers?

For example, i want to store this text file in an 2d array

13 4 652
2 343    
5 86 9 41
2 18
19

If someone can point me in the right direction, that would be very much helpful. Thanks


Solution

  • You can use split() for Strings. If you use white-space as a delimiter, it will return an array of Strings, where each number in the line will map to one slot in the array. Then, loop through the array and use Integer.parseInt().

    Another way to do it would be to feed the output from nextLine() into another Scanner and use nextInt() to retrieve the numbers.