I would like to know how can I access the file system from an EJB 3 bean?
I searched the Internet on the subject and haven't found a good answer.
Some suggest using the java.io/java.nio even though the specification prohibits this usage. Most application servers seem to allow the access to this API anyway.
Another idea would be to use an JCA connector to access the file system or a LDAP directory.
What I want to do this to avoid the use of BLOB in the database when a simple file would be a much better solution in terms of performance and used resources.
How would you solve this problem?
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.