Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从res文件夹加载文件时出现NullPointerException-Java_Java_Audio - Fatal编程技术网

从res文件夹加载文件时出现NullPointerException-Java

从res文件夹加载文件时出现NullPointerException-Java,java,audio,Java,Audio,所以我使用这个代码: ClassLoader classLoader = getClass().getClassLoader(); File audioFile = new File(classLoader.getResource("pop.wav").getFile()); AudioInputStream audioStream = AudioSystem.getAudioInputStream(audioFile); AudioFormat format

所以我使用这个代码:

    ClassLoader classLoader = getClass().getClassLoader();
    File audioFile = new File(classLoader.getResource("pop.wav").getFile());

    AudioInputStream audioStream = AudioSystem.getAudioInputStream(audioFile);

    AudioFormat format = audioStream.getFormat();

    DataLine.Info info = new DataLine.Info(Clip.class, format);

    Clip audioClip = (Clip) AudioSystem.getLine(info);
    audioClip.open(audioStream);
    audioClip.start();
但每次它都会给我一个NullPointerException。
文件(pop.wav)在src/res中。但是如果a将它放在我的桌面上,而不是
classLoader.getResource(“pop.wav”).getFile()
I将
C:/Users/gebruiker/desktop/pop.wav
放在它工作。

资源是而不是文件

试试这个:

AudioInputStream audioStream = AudioSystem.getAudioInputStream(getClass ().getResourceAsStream ("/res/pop.wav"));

当然,请检查pop.wav的路径。有时JAR(/POP.WAV)中的绝对路径更易于管理。

本帖中可能的副本的可能副本:你会考虑接受这个答案吗?Merry Xmas您的jar中的pop.wav在哪里?我不知道这是否重要,但此方法是在鼠标按下的事件上调用的。在这种情况下,请尝试/res/pop.wav。很抱歉,我不理解它。我不是一个真正有经验的Java程序员。