Search code examples
javaejbjava-ee-7ejb-3.2

Is it acceptable to access the file system in EJB?


Is it acceptable to use types from the java.io and java.nio packages to access the file system and manipulate files in EJB?


Solution

  • No, you are not allowed to do that because if the application will be clustered at some point, you never know to what location has your files been saved. So file manipulation in Java EE environment is rather unsafe operation.

    The way to do this safely would be probably to have service in JNDI which will take care about your object serialization - see example

    ByteArrayOutputStream baos= new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(myObj);
    
    new InitialContext().bind("path/to/FileManipulator", baos.toByteArray());
    

    See also this answer for further explanation. Also here is an article which describes what specification says about using java.io in EJB.