Write an object
As opposed to writng a text file, we will save an instance of a object.
Well need to apply som minor changes to the object we would like to save.
package net.westsoftware.data;
import java.io.Serializable;
public class MyObject implements Serializable{
private String myValue;
public MyObject(){
myValue="OK";
}
}
The only thing that need to be added to the object is
import java.io.Serializable and implements Serializable.
This enables the object to be saved.
The code for saving the object:
import java.io.*;
...
public void saveData(MyObject myObj, String file) throws IOException{
File f = new File(file);
if(!f.exists()){
f.createNewFile();
}
FileOutputStream f_out = new FileOutputStream(file);
ObjectOutputStream obj_out = new ObjectOutputStream (f_out);
obj_out.writeObject ( myObj );
obj_out.close();
}
Input for the method is an instance of your object and the absolute path for the file you want to create.
Normally we'll prefix the object filename you want to save with .dat.