It is necessary to read a two-dimensional array from a file (written in binary form), found the code for the recording function in one of the forums, but the topic was created a long time ago and no one has yet responded. Help to write the read function, provided that the variable this.Array is declared in the class.

public boolean Save(String path) { try { DataOutputStream out = new DataOutputStream(new FileOutputStream(path)); for (byte i=0; i<this.Array.length;i++) { for (byte j=0;j<this.Array[0].length;j++) { out.writeInt(this.Array[i][j]); } } return true; } catch (IOException e) { return false; } } 
  • What kind of unfinished piece of code? - Denis
  • 2
    What exactly is your problem when reading an array? What exactly does not work? Can't read exactly two-dimensional array? Or do not know how to read from binary files? And add the code, and then you got a piece. - Arsenicum

2 answers 2

Sample code to read from a binary file into a matrix:

 int lineCount = 0; while ((line = bf.readLine()) != null) { String[] numbers = line.split(" "); for ( int i = 0 ; i < 3 ; i++) matrix[lineCount][i] = Double.parseDouble(numbers[i]); lineCount++; } 

Source: enSO .

    Thank you all for your help, adding up all the answers:

     class Map { private int Array[][]; ... public boolean Save(String path) { try { DataOutputStream out = new DataOutputStream(new FileOutputStream(path)); out.writeInt(this.Array.length); out.writeInt(this.Array[0].length); for (byte i=0; i<this.Array.length;i++) { for (byte j=0;j<this.Array[0].length;j++) { out.writeInt(this.Array[i][j]); } } return true; } catch (IOException e) { return false; } } public boolean Read(String path) { try { DataInputStream in = new DataInputStream(new FileInputStream(path)); this.Array = new int[in.readInt()][in.readInt()]; for (int[] args : this.Array) { for (int j = 0; j < args.length; j++) { args[j] = in.readInt(); } } return true; } catch (IOException e) { return false; } } } 
    • Markdown does not understand the <pre> and <code> tags, use four spaces to indent (select your entire code block and press the {} button in the editor to add indents). You can also edit your answers and questions, and not create new ones unnecessarily. - zRrr