I want read some data from file, how should I do?
Writing code using java.io package in an EJB will work fine, but you are breaking the specification. On the other hand, if you have an existing file and you really must read it, my proposal is to do so!
But you should be aware of several thing when doing this:
- You are breaking the spec!
- You are not J2EE compliant anymore (if that is important).
- You will have transactional problems if you do anything else than reading the file!!!
- If the file is read often, you may have problems when many threads are reading the same file.
- If your application is running in a cluster, you must have the file on all machines in the cluster (or on a shared disk).
And where do you store the filename? My proposal is to put it as an <env-entry> in ejb-jar.xml.
If it is a properties file (and you are the owner of it), I recommend you to use <env-entry> in ejb-jar-xml.
First of all, the topic is misleading. You can use the java.io package from EJB just fine. What you shouldn't do is use it to access the local file system.
My two common solutions are:
- place the file in the JAR and load it from the classpath. This solves the distribution problems (JAR will get copied to every node in the cluster).
- if the above is not sufficient (and there are several reasons why that might be the case) use a URL resource pointing to some central HTTP server or something.
Thanks for your reply. With theses answeres, I think I can use the I/O operations, because I currently don't use the cluster, and my file just a property file. But I have a doubt, when I use the I/O operation in stateless session bean, sometimes, it will throw an null pointer exception, but not always!
If it's a properties file then placing them in the JAR sounds appropriate.
About the null pointer exception, I can't guess what might be causing it without seeing the stack trace and relevant code.
From section 24.1.2 in the EJB 2.0 spec:
"An enterprise bean must not use the java.io package to attempt to access files and directo-ries
in the file system.
The file system APIs are not well-suited for business components to access data. Business components
should use a resource manager API, such as JDBC, to store data."
But if u are not that orthodox u can definately use that in ur EJBs...but do not expect it to maintain Transaction,Security etc.... and also if a file is read often, you may have problems with, many threads reading the same file...
If its just a props file, you could also define them in the DD.
and also if a file is read often, you may have problems >>with, many threads reading the same file...
What problems? I think if many threads write the same file, it will cause some problem, but I only read it.
File contention issues, if the filesystem on your given system will lock that file and the other threads have to wait for it. As it's a properties file it won't be a big deal.