简体   繁体   English

对ClassLoader.getResourceAsStream()或Class.getResourceAsStream()进行故障排除

[英]Troubleshooting ClassLoader.getResourceAsStream() or Class.getResourceAsStream()

I work on an application where the war has a directory structure like the following: 我在战争具有如下目录结构的应用程序上工作:

ear/war/modules/configuration/gsrc/<java packages start here>

However, I want to dynamically read a file that lives here: 但是,我想动态读取位于此处的文件:

/ear/war/modules/configuration/some/other/dir/somefile.csv

I have tried many permutations of the normal ClassLoader.getResourceAsStream() and Class.getResourceAsStream() to try to get a handle to that resource all of which come up with null such as: 我已经尝试了正常ClassLoader.getResourceAsStream()和Class.getResourceAsStream()的许多排列,以尝试获取对该资源的句柄,所有这些句柄都带有null,例如:

ClassLoader.getResourceAsStream("/modules/configuration/some/other/dir/somefile.csv")
ClassLoader.getResourceAsStream("/configuration/some/other/dir/somefile.csv")
ClassLoader.getResourceAsStream("/some/other/dir/somefile.csv")
Class.getResourceAsStream("../some/other/dir/somefile.csv")
Class.getResourceAsStream("../../some/other/dir/somefile.csv")
Class.getResourceAsStream("../../../some/other/dir/somefile.csv")

My assumption is I'm using a classloader who's root scope is the gsrc directory where the code lives. 我的假设是我正在使用一个类加载器,其根范围是代码所在的gsrc目录。 What is the appropriate way to troubleshoot this? 解决此问题的适当方法是什么?

For instance I was hoping I could print out something like ClassLoader.rootDirectory() to figure out what the root directory of the classloader is. 例如,我希望可以打印出类似ClassLoader.rootDirectory()之类的内容,以弄清类加载器的根目录是什么。 Then I could print out the root dir of this classloader and it's parent(s), etc. 然后,我可以打印出该类加载器的根目录及其父目录,依此类推。

The runtime is jetty locally, but websphere in all other regions. 运行时在本地是码头,但在所有其他区域都是Websphere。

My Eclipse project has the following structure: 我的Eclipse项目具有以下结构:

C:\\workspace\\ProjectName\\src\\com\\my\\package\\resources\\myfile.properties C:\\ workspace \\ ProjectName \\ src \\ com \\ my \\ package \\ resources \\ myfile.properties

So, to actually load this file I'm doing this: 因此,要实际加载此文件,我正在这样做:

getClass().getResourceAsStream("/com/my/package/resources/myfile.properties")

I hope this example can help you. 我希望这个例子能对您有所帮助。

Either put the file in WEB-INF and access it from a servlet using 可以将文件放在WEB-INF中,然后使用

getServletContext().getResourceAsStream("/WEB-INF/somefile.csv");

or place it anywhere on the filesystem and access it either with the Java File API or Apache commons-io . 或将其放置在文件系统上的任何位置,并使用Java File API或Apache commons-io对其进行访问

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

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