Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
136 views
in Technique[技术] by (71.8m points)

java - How to access the file system from an EJB 3?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...