Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Read numbers from txt.file and generate 2d array

For example we have file("Test2") which contains:

1 2 3 4 5
1 2 3 4 0
1 2 3 0 0
1 2 0 0 0
1 0 0 0 0
1 2 0 0 0
1 2 3 0 0
1 2 3 4 0
1 2 3 4 5 

And we want to read it from file.
In this example the numbers of rows and columns is known!!!

   public class Read2 {
    public static void main(String[] args) throws FileNotFoundException {
        Scanner s = new Scanner(new FileReader("Test2"));
        int[][] array = new int[9][5];
        while (s.hasNextInt()) {
            for (int i = 0; i < array.length; i++) {
                String[] numbers = s.nextLine().split(" ");
                for (int j = 0; j < array[i].length; j++) {
                    array[i][j] = Integer.parseInt(numbers[j]);
                }
            }
        }
        for (int[] x : array) {
            System.out.println(Arrays.toString(x));
        }
         // It is a normal int[][] and i can use their data for calculations.
        System.out.println(array[0][3] + array[7][2]);
    }
} 

// Output
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 0]
[1, 2, 3, 0, 0]
[1, 2, 0, 0, 0]
[1, 0, 0, 0, 0]
[1, 2, 0, 0, 0]
[1, 2, 3, 0, 0]
[1, 2, 3, 4, 0]
[1, 2, 3, 4, 5]
7//result from sum

My question is: if i have a file with x=rows and y=columns(unknown size) and i want to read numbers from file and put them is 2d array like in previous example. What type of code should i write?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Here is a solution using the stream API:

var arr = new BufferedReader(new FileReader("PATH/TO/FILE")).lines()
                .map(s -> s.split("\\s+"))
                .map(s -> Stream.of(s)
                        .map(Integer::parseInt)
                        .toArray(Integer[]::new))
                .toArray(Integer[][]::new);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading