【问题标题】:file not found exception while trying to read file in netbeans尝试在netbeans中读取文件时找不到文件异常
【发布时间】:2015-09-25 06:04:43
【问题描述】:

我正在制作一个简单的应用程序来用 Java 播放声音。当我将音频文件保存在 D: 磁盘中时,我可以做到这一点。这是代码

in = new FileInputStream("D:\\"+selectedSounds[position]+".wav");
//Some code for playing audio

然后我将音频文件放在 Jframe 类所在的同一个包中。但是当我运行它时会提示 fileNotFound 异常。谁能告诉我为什么会这样。

in = new FileInputStream(selectedSounds[position]+".wav");
// I have also tried 
    new FileInputStream("./"+selectedSounds[position]+".wav");

这是文件路径

【问题讨论】:

  • 这与Swing有什么关系?不要仅仅因为这是正在使用的 GUI 工具包就在帖子上打标签。这同样适用于您的 IDE。标签旨在表示问题与什么相关。

标签: java file embedded-resource filenotfoundexception fileinputstream


【解决方案1】:

一旦程序打包为 Jar,您将无法访问包含在“源包”中的 wave 文件,因为这些文件将嵌入 Jar 本身中,并且不再作为文件访问。

相反,您应该使用Class#getResourceAsStream,例如...

try (InputStream in = getClass().getResourceAsStream("/PlayAudio/" + selectedSounds[position]+".wav")) {
    // You now have an InputStream to your resource, have fun
} catch (IOException | NullPointerException exp) {
    exp.printStackTrace();
}

【讨论】:

    猜你喜欢
    • 2019-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多