Search code examples
javamultidimensional-arraystorage

2-Dimensional array storage


I have recently stumbled upon this problem. I want to store a 2-dimensional int array in a file to be read later. Is there any way of doing this other than simple txt.file? (Java as programming language)


Solution

  • As indicated by @Andy you can use ObjectOutputStream to serialize array to a file

    int[][] intArray = new int[5][5];
    //Code to populate array
    
    // serialize array
    FileOutputStream fos = new FileOutputStream("array.dat");
    ObjectOutputStream oos = new ObjectOutputStream(fos);
    oos.writeObject(intArray);
    

    And then it can be read back as an array from file using ObjectInputStream

    FileInputStream fis = new FileInputStream("array.dat");
    ObjectInputStream iis = new ObjectInputStream(fis);
    intArray = (int[][]) iis.readObject();
    

    Hope this helps.