Gradle做了什么是完全可以预料到的. src / main / java和src / main / resources目录分别存储代码和资源. resources文件夹包含所有非java代码,如图像,声音等.
创建jar文件时,资源目录的内容将按原样复制(维护包结构).请注意,click.mp3和bgm.mp3是声音包的成员.
因此,当您要加载资源时,应该(通常)不使用文件路径来完成.而是使用包结构来做到这一点.在这里,由于声音和SoundPlayer具有相同的包,即声音,您可以使用SoundPlayer类加载如下资源:
public SoundPlayer(String filename) {
URL resource = SoundPlayer.class.getResource(filename);
Media soundMedia = new Media(resource.toExternalForm());
mediaPlayer = new MediaPlayer(soundMedia);
}
来自Javadocs
public String toExternalForm()
Constructs a string representation of this URL. The string is created by calling the toExternalForm method of the stream protocol handler for this object.
本质上,toExternalForm()函数为给定资源创建适当的URL.
这是一个完整的例子.
// build.gradle
apply plugin: 'java'
apply plugin: 'application'
source