在Java代码中查找文件

Sgt*_*tud 0 java eclipse file embedded-resource

我正在尝试制作一个播放声音的简单应用程序.我有一个名为sound.wav的声音文件位于我的java项目中(使用eclipse btw).我不确定如何导航到声音文件.问题是我不知道如何通过代码导航到声音文件.我现在正在运行的是抛出空指针异常,即.该文件不存在.到目前为止,这是我的代码:

    private static Sound sound;

public static void main(String[] args) {
    JFrame j = new JFrame("Sound");
    j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    j.setSize(300, 150);
    sound = new Sound("/Users/Chris/Desktop/Workspace/Sound/sound.wav");
            //this is the problem line
    JButton play = new JButton("Play");
    play.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            sound.play();               
        }

    });

    j.add(play,BorderLayout.SOUTH);
    j.setVisible(true);
}
Run Code Online (Sandbox Code Playgroud)

这是我的声音类的代码:

    private AudioClip clip;

public Sound(String fileName) {
    try {
        clip = Applet.newAudioClip(Sound.class.getResource(fileName));
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}

public void play() {
    try {
        new Thread(){
            public void run() {
                clip.play();
            }
        }.start();
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}
Run Code Online (Sandbox Code Playgroud)

JB *_*zet 5

Class.getResource(),正如其javadoc所示,从类路径中读取资源.不是来自文件系统.

要么从文件中读取,要么使用文件IO(即a FileInputStream),要么想从类路径中读取,并且应该使用Class.getResource()并传递资源路径,从类路径的根开始.例如,如果sound.wav位于运行时类路径中,则在包中com.foo.bar.sounds应该是代码

Sound.class.getResource("/com/foo/bar/sounds/sound.wav")
Run Code Online (Sandbox Code Playgroud)