I have a J2EE web application:jsp+EJB,there is a new requrement for my application.there are some file put on specified folder on the server,I was asked to read and write infomation to these files with my application.what's the best way to do that,I know the java is OS nature,so it's hard to make it interact with OS file system,is there any patterns around this issue?
Actually, Java interacts with the file system pretty nicely, although File I/O is not as easy as it is in languages like VB and Perl. Everything you need is in the java.io package. Object like java.io.File and java.io.FileReader/Writer understand both file paths for the OS or OS-neutral file URLs: file://...
The easiest thing to do is to read the entire file into memory, and then write the updated file back to the file system. This works pretty well unless the files are large. If you want to locate and alter specific parts of an existing file, you have to use the java.io.RandomAccessFile class, which is trickier than the other I/O classes.
I read the EJB specification. The part of the specification relevant here is under the section entitled Programming Restrictions, and it states the following about accessing the filing system.
An enterprise bean must not use the java.io package to attempt to access files and directories in the file system.
so,I don't think it is good to use file IO in j2ee,but what's the way to work around?
There is no reason why you can't do your File I/O outside your EJBs, in a regular Java object called directly by your Servlet/JSP.
The main reason why you shouldn't do this kind of File I/O in an EJB is thread-synchronization issues; your File I/O logic will need to be properly synchronized to prevent multiple threads from trying to read/write to your file at the same time.
If for some reason you can't access the file from objects in your web layer (e.g. because it is on a different machine), this is one of those things where if you write your code with care, you can ignore the restrictions of the EJB specification and use File I/O anyway. Personally, though, I will go with the simple Java object approach if you can make that work.