0

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?

3
  • 2
    You can use a List<List<Integer>>. Commented Aug 5, 2022 at 15:16
  • Is this for an assignment? If so, are you required to use loops? Commented Aug 5, 2022 at 18:18
  • Cheng Thao, you can use every thing(preferably something simple and doesn't matter if the code is long) Commented Aug 6, 2022 at 7:53

3 Answers 3

1

Using try with resources will close the file once the stream has been processed.

  • use Files.lines to return a stream.
  • split the lines on some delimiter to expose the ints. One or more spaces is the chosen delimiter here.
  • then simply convert to an int and package in an int[][] array.
  • upon any exception, null is returned.
public static int[][] readInts(String fileName) {
    try (Stream<String> lines = Files.lines(Path.of(fileName))) {
        
        return lines.map(line->Arrays.stream(line.split("\\s+"))
                        .mapToInt(Integer::valueOf)
                        .toArray())
                .toArray(int[][]::new);
        
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
    return null;
}

Note: The above presumes that each row of the array is on a separate line in the file. Lines containing different counts of integers would also work.

Sign up to request clarification or add additional context in comments.

Comments

0

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);

2 Comments

Note that it is probably a good idea to close the BufferedReader after all the lines have been read.
Wrap it in a try-with-resources block to ensure the file is closed. That can be on the BufferedReader or on the Stream<String> which will close the underlying I/O object.
0

Just as @Andy Turner said, use List<List<Integer>>, since List does not compulsively demand its length while initialing. Code is this:

public class Read2 {

    public static void main(String[] args) throws FileNotFoundException {
        Scanner s = new Scanner(new FileReader("Test2"));
        List<List<Integer>> list = new ArrayList<>();
        // scan digits in every line
        while (s.hasNextLine()) {
            String str = s.nextLine();
            String[] strSplitArr = str.split(" ");
          list.add(Arrays.stream(strSplitArr)
              .map(Integer::parseInt)
              .collect(Collectors.toList()));
        }
        for (List<Integer> integersInOneLine : list) {
            System.out.println(integersInOneLine.stream()
                      .map(Object::toString)
                      .collect(Collectors.joining(", ", "[", "]")));
            System.out.println();
        }
    }
}

Comments

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.