Java &引用;找不到指定的文件";,多次检查&;看起来不错
为什么我的文件没有被正确读取?我检查了,res文件夹是这个项目中的一个资源Java &引用;找不到指定的文件";,多次检查&;看起来不错,java,audio,embedded-resource,clip,Java,Audio,Embedded Resource,Clip,为什么我的文件没有被正确读取?我检查了,res文件夹是这个项目中的一个资源 public class Testing { private File file; private Clip clip; private AudioInputStream audioIn; public Testing() { String path = "/res/shot.mp3"; file = new File(path); Sy
public class Testing {
private File file;
private Clip clip;
private AudioInputStream audioIn;
public Testing() {
String path = "/res/shot.mp3";
file = new File(path);
System.out.println(file.toString());
try {
audioIn = AudioSystem.getAudioInputStream(file);
clip = AudioSystem.getClip();
clip.open(audioIn);
clip.start();
} catch(Exception e) {
e.printStackTrace();
}
// java.io.FileNotFoundException: \res\shot.mp3
// (The system cannot find the path specified)
}
public static void main(String[] args) {
new Testing();
}
}
我的包浏览器
我尝试将路径更改为
/SoundTest/res/shot.mp3
,但仍然没有成功。有什么想法吗?/code>/res/shot.mp3是一条绝对路径。仅当res
位于文件系统的根目录中时,此操作才有效。您说“资源文件夹是此项目中的一个文件夹”。从您的屏幕截图来看,目录结构类似于
/home/your_user_dir/your_project_dir
/src ...
/bin
/res
因此,您需要更改文件
对象的创建,使其具有正确的相对路径或使用绝对路径
你可以用
InputStream is = this.getClass().getClassLoader().getResourceAsStream("/res/shot.mp3");
然后使用AudioSystem创建您的AudioInputStream
。getAudioInputStream(InputStream)
--
所以把你的代码改成
String path = "/res/shot.mp3";
InputStream is = this.getClass().getClassLoader().getResourceAsStream(path);
try {
audioIn = AudioSystem.getAudioInputStream(is);
clip = AudioSystem.getClip();
clip.open(audioIn);
clip.start();
} catch(Exception e) {
e.printStackTrace();
}
无论存在何种文件,是否确实要使用
.mp3
-文件AudioSystem.getAudioFileTypes()
返回我的计算机上支持的WAVE
、AU
和AIFF
类型
此外,您在问题中提出的异常是否与您共享的源代码相匹配?在您的代码中,它是shot.mp3,但异常是指.wav
文件。不,您不能使用
file = new File(path);
audioIn = AudioSystem.getAudioInputStream(file);
如果要获取资源文件夹中的文件,必须使用方法getResource()
在代码中更改此选项:
URL url = Testing.class.getResource("/res/shot.mp3");
AudioInputStream audioIn = AudioSystem.getAudioInputStream(url);
Clip clip = AudioSystem.getClip();
clip.open(audioIn);//surround with try catch block i didn't use here
希望这可能会有帮助不走运的可能复制品。我得到了相同的错误,除了控制台中的路径现在显然是shot.mp3。
/res/shot.mp3
是绝对路径。仅当res
位于文件系统的根目录中时,此操作才有效。您说“资源文件夹是此项目中的一个文件夹”。项目位于何处?此文件必须是真实文件还是将在jar中打包?@WilliamBurnham项目位于我的一个eclipse工作区文件夹中,然后位于该文件夹中的是bin、src等以及我的res文件夹。“这将为您提供一个可以转换为文件对象的url。”不是a)如果它来自网络或b)在罐子里。。URL可以覆盖比文件更多的数据源,因此,一旦代码获得有效的URL,要么直接从中获取输入流,要么(使用Java Sound更安全,它通常需要缓冲输入流)直接使用URL。@AndrewThompson感谢您的评论,我更新了答案是的,对不起。我试过同时使用.mp3和.wav文件,但忘了提到这一点。