在快照中所示的utility
包中,有一个类Constants
。在与utility
相同的目录中,有一个名为sounds
的folder
,快照中也显示了这个名称。到目前为止,我已经给出了.wav
文件的完整路径。
Like W:/UnderTest/Blaah/Blaaaaah/Foo/sounds/file.wav
我应该如何给出路径,以便当我创建一个.jar
文件,声音仍然工作。我试过这个:
../sounds/Player_1.wav
但这不起作用,我得到了java.io.FileNotFoundException: ..\sounds\Player_1.wav (The system cannot find the path specified)
发布于 2013-04-06 20:53:00
试试这个..。
URL url = Constants.class.getResource("/sounds/file.wav");
当前获取文件路径的url .
发布于 2013-04-06 21:09:07
在这种情况下,最好加载相对于根类路径的资源:
URL soundURL = Thread.currentThread().getContextClassLoader()
.getResource("/sounds/file.wav");
您还可以将资源作为流获得:
InputStream soundURLStream = Thread.currentThread().getContextClassLoader()
.getResourceAsStream("/sounds/file.wav");
这与Class.getResource
之间的主要区别是,Class.getResource
假定所提供的路径相对于类层次结构中的及其位置。因此,给定相对路径“/ the /file.wav”,从类getResource
调用utility.Constants
,将尝试从包utility.sounds
解析file.wav
资源。而使用类加载器和相同的相对路径时,资源将从sounds
中解析。微妙但重要的区别。
https://stackoverflow.com/questions/15858968
复制相似问题