javaarraysalgorithmbufferedreader

Convert 2 text line of integers into 2D array


I have some text lines like this

14 14 14 14

32 32 32 32

I want to convert into 2D array with BufferReader. Any help?


Solution

  • I am hoping you are looking for convert string array in buffer

    public int[][] convertTo2DArray(String filename) {
        int[][] array = null;
        
        try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
            String line;
            int row = 0;
            
            while ((line = reader.readLine()) != null) {
                String[] elements = line.split(" ");
                
                if (array == null) {
                    array = new int[elements.length][];
                }
                
                array[row] = new int[elements.length];
                
                for (int i = 0; i < elements.length; i++) {
                    array[row][i] = Integer.parseInt(elements[i]);
                }
                
                row++;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        return array;
    }
    
    
    String filename = "path/to/your/file.txt";
    int[][] result = convertTo2DArray(filename);