I just wrote this code... and tested it ... seems to work perfectly :-)
In this code I saved a 2D array, offcourse you could as well replace the int[][] of the 2nd argument definition and make it any other kind of object ... you can even save instances of your own classes. (condition: the class needs to implement the Serializable interface).
As you can see the files are also zipped. You can leave that out if you do not like it.Code:public void saveArray(String filename, int[][] output_veld) { try { FileOutputStream fos = new FileOutputStream(filename); GZIPOutputStream gzos = new GZIPOutputStream(fos); ObjectOutputStream out = new ObjectOutputStream(gzos); out.writeObject(output_veld); out.flush(); out.close(); } catch (IOException e) { System.out.println(e); } } public int[][] loadArray(String filename) { try { FileInputStream fis = new FileInputStream(filename); GZIPInputStream gzis = new GZIPInputStream(fis); ObjectInputStream in = new ObjectInputStream(gzis); int[][] gelezen_veld = (int[][])in.readObject(); in.close(); return gelezen_veld; } catch (Exception e) { System.out.println(e); } return null; }
The (int[][]) is for casting the object to the original type. So if you change the code to make it change another type of instance then do not forget to change it !
I used this code for a supermario game to save and read my levels. It is easier than writing and reading from XML files.


Reply With Quote