Java EE 规范似乎不允许从 EJB 读取文件,如下一个链接中明确所述:
http://java.sun.com/blueprints/qanda/ejb_tier/restrictions.html#file_access
它说:
Enterprise beans aren't allowed to access files primarily because files are not transactional resources. Allowing EJBs to access files or directories in the filesystem, or to use file descriptors, would compromise component distributability, and would be a security hazard.
那么我应该如何读取应用程序服务器中的文件?
最佳答案
我同意所有反对此类操作的观点,您引用的链接中对此进行了很好的解释。该链接还建议了访问业务数据的首选方式,即通过 JDBC 接口(interface)。
但是,使用 GlassFish,我可以从 @Stateless
@EJB
以及 中打开并读取驻留在 Web 文件夹中的文件。 @ApplicationScoped
CDI
Bean。我使用 ClassLoader
来实现此目的:
@Stateless
@LocalBean
public class MyBean {
@PostConstruct
public void init() {
ClassLoader loader = LicenseMessage.class.getClassLoader();
InputStream in = loader.getResourceAsStream("../../resources/myFile.txt");
}
}
关于java - 从 EJB 读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10735221/