我需要在web应用程序的src/main/resources文件夹中查找图像。它是一个基于Apache CXF SAOP的web应用程序。
我们在jboss env(jboss-eap-6.4)中运行它
在构建了war之后,部署了相同的应用程序。
但是,我无法获得上述文件的正确路径。请提个建议。
我已经尝试了多个选项。
File logo= new File("src/main/resources/image.jpg");
logo.getAbsolutePath(); // This works great when Junit tested, however breaks with the server. 这也不管用-
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
contextClassLoader.getResource("image.jpg").getPath();发布于 2019-01-13 00:42:26
由于您使用的是Maven,因此来自src/main/resources的文件将自动放在类路径中。
要从类路径加载资源,请使用类似以下内容:
InputStream in = getClass().getResourceAsStream("/image.jpg");但是,获取资源的路径或将其作为File打开可能并不总是有效的,因为文件可能仍然存储在.war文件中。因此,class.getResource()将返回一个只有应用服务器的类加载器才能识别的URL。
发布于 2020-01-27 08:27:02
这是我在Maven项目中的文件结构:
src/main/resources/
src/main/resources/META-INF
src/main/resources/adir
src/main/resources/adir/afile.json最后,这对我起作用了:
String resourceName = "adir/afile.json";
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
URL resource = classLoader.getResource(resourceName);
InputStream iStream = resource.openStream();
byte[] contents = iStream.readAllBytes();
System.out.println(new String(contents));HTH,托马斯
https://stackoverflow.com/questions/54161215
复制相似问题