简体   繁体   English

JavaEE Web-从/ src / main / resources访问文件

[英]JavaEE web - accessing files from /src/main/resources

I have a web application I'm writing and I need to access two files (xlsx) files. 我有一个正在编写的Web应用程序,我需要访问两个文件(xlsx)。 I'm not sure which web server I'll be using (Tomcat, Glassfish, or Other). 我不确定我将使用哪个Web服务器(Tomcat,Glassfish或其他)。

In my application I have a file located in: 在我的应用程序中,我有一个文件位于:

/src/main/resources/Analysis_Template.xlsx

I'm trying to figure out how to access it from code. 我试图弄清楚如何从代码中访问它。

The following code seemed to "sort of" work in WildFly but not in GlassFish 以下代码似乎在WildFly中“起作用”,但在GlassFish不起作用

URI templateURI = this.getClass().getResource("/Analysis_template.xlsx").toURI();
File f = new File(templateURI.getPath());

Although this code did not crash f.canRead() returned false so I think it probably wasn't working. 尽管这段代码没有崩溃f.canRead()返回false,所以我认为它可能无法正常工作。 When I tried to run this under GlassFish things did not go well and it straight up crashed on the first line of code with a java.lang.NullPointerException 当我尝试在GlassFish下运行此程序时,一切进展不顺利,并且在代码的第一行中直接使用java.lang.NullPointerException崩溃了

Any suggestions I'm sure its super obvious I'm just missing it. 我确信任何建议都非常明显,我只是想念它。

--- Edits and Notes -- -编辑和注释-

[I do end up with a WAR archive] [我确实得到了WAR存档]

With WildFly the file is: 使用WildFly ,文件为:

/usr/local/opt/wildfly-as/libexec/standalone/deployments/fleetForecast-1.0-SNAPSHOT.war/WEB-INF/classes/ANALYSIS_template.xlsx

Glassfish From what I can tell netbeans reports: In-place deployment at Glassfish的从我可以告诉NetBeans的报告: 在就地部署

~/devel/fleetforecast/target/fleetForecast-1.0-SNAPSHOT

And I find my file at: 我在以下位置找到我的文件:

~/devel/fleetforecast/target/fleetForecast-1.0-SNAPSHOT/WEB-INF/classes/ANALYSIS_template.xlsx

I have to read this file into a File object to pass to some code to create a set of XLSX files which will eventually be served up to the user. 我必须将此文件读入File对象,以传递给一些代码来创建一组XLSX文件,这些文件最终将提供给用户。

Try like this. 尝试这样。 When war files are packaged any files in /src/main/resources end at root level of your webapp. 打包war文件后,/ src / main / resources中的任何文件都以您Webapp的根目录结尾。 I think you should also prefer using getResourceAsStream over getResource because the later can only read files from file system. 我认为您也应该优先使用getResourceAsStream而不是getResource,因为后者只能从文件系统读取文件。

BufferedReader br = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/Analysis_template.xlsx")));
// Now do something with br

I hope it helps.:) 希望对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM