2011-03-29 99 views
1

我在java程序读取的路径中有hibernate.cfg.xml和test.txt。现在,当我使用maven创建jar时,这些文件不存在。所以,我读,我应该放在资源文件夹,所以现在我的目录结构是如何从jar中添加和读取资源文件

SCR - > main->的Java

 ->resources 

现在我可以看到在jar文件,但它们不是资源文件夹内 它bascically

myjar.jar - > COM(源代码)

 -> META -INF 
     -> hibernate.cfg.xml 
     -> test.txt 

我尝试使用

的getClass()。的getResourceAsStream访问( “的test.txt”)

,但得到空..

让我知道什么步骤错了吗?

回答

2

看着this articlegetClass().getResourceAsStream("/test.txt")是否有所作为?

+0

getClass()。getResourceAsStream(“/ test.txt”)这将工作.. – harshit 2011-03-31 20:42:56

2

getClass().getResourceAsStream(name)搜索在同一目录作为此方法被称为类的资源是。

例如,你在你打电话getClass().getResourceAsStream("test.txt")同一目录有A类和资源test.txt。如果它位于某个子目录中,则需要在namegetClass().getResourceAsStream("subdir/test.txt")中表示该目录。

我还没有测试过,但是在目前的目录中应该可以使用:getClass().getResourceAsStream("../test.txt")

+0

这不工作 – harshit 2011-03-29 02:01:08