The reason that you are disallowed from file system access in EJBs is that you have no control over how your application runs within a (Java EE) Container. For example, your application may be run across a cluster of servers, in which case saving some object to a directory on one server is likely to be of little use. (You may have a network file-system of course, so the restriction may not apply).
One option may be to use the JNDI implementation which comes with your Container. You will likely be able to save a raw byte[]
array at some JNDI location, so you could always save down the serialized form of the object:
ByteArrayOutputStream baos= new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(myObj);
//Now save into JNDI
new InitialContext().bind("path/to/myobject", baos.toByteArray());
This can be looked up later and re-converted into your object:
byte[] bs = (byte[]) new InitialContext().lookup("path/to/myobject");
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bs));
MyObj myObj = (MyObj) ois.readObject();
Alternatively you could use the java.beans
persistent XML (i.e. XMLDecoder
, XMLEncoder
) to encode your instance as an XML string an save that into JNDI.