javamultidimensional-arrayintegerreaderbuffered

Read from txt a 2D arraylist


I have this 2d arraylist and I want to read it from my txt file using buffer Reader(Java) . Any help?

//my 2d arraylist with integers 1 2 3 4 5 6 7 8 9 10 11 12


Solution

  • Your input is 1d array, so to read it as 2d array - you have to provide (or get from somewhere) width and/or height of the resulting 2d array.

    Here is example:

    // Prepare memory for the output
    int width=4;
    int height=3;
    
    int[][] d2 = new int[height][width];
    
    try {
        BufferedReader br = new BufferedReader(new FileReader("test.txt"));
        String fileContent = "";
        String line;
    
        while ((line = br.readLine()) != null) {
          fileContent += line + " ";
        }
    
        String ints[] = fileContent.split("\\p{javaWhitespace}+");
    
        for(int i=0;i<height;i++) {
          for (int j = 0; j < width; j++) {
            if((i * width + j) >= ints.length) throw new RuntimeException("Not enough ints :-(");
            d2[i][j] = Integer.parseInt(ints[i * width + j]);
          }
        }
    } catch (Exception e) {
      e.printStackTrace();
    }
    
    /// Now you have the 2d_array in d2!