我想將一個.wav文件加載到內存中,但它一直告訴我該文件不存在。Java獲取資源的相對路徑
String filename;
public MyClass(String _filename){
filename = _filename;
}
public void run(){
InputStream in = View.class.getClassLoader().getResourceAsStream("/sounds/"+filename);
File inputFile = new File(in.toString());
if(!inputFile.exists()){
System.err.println("Wave file not found: " + in.toString());
return;
}
}
控制檯:
Wave file not found: [email protected]
Wave file notfound: [email protected]
的文件是在程序包的文件夾。這是一個在
myPackage/sounds/write.wav
編輯:
其實我要加載的聲音:
InputStream in = this.getClass().getResourceAsStream("sounds/"+filename);
AudioInputStream audioInputStream = null;
try {
audioInputStream = AudioSystem.getAudioInputStream(in);
} catch (UnsupportedAudioFileException e1) {
e1.printStackTrace();
return;
} catch (IOException e1) {
e1.printStackTrace();
return;
}
但控制檯仍與錯誤:
Exception in thread "Thread-6" Exception in thread "Thread-7" java.lang.NullPointerException at com.sun.media.sound.SoftMidiAudioFileReader.getAudioInputStream(Unknown Source) at javax.sound.sampled.AudioSystem.getAudioInputStream(Unknown Source) at com.chrissman.threads.AePlayWave.run(AePlayWave.java:47) java.lang.NullPointerException at com.sun.media.sound.SoftMidiAudioFileReader.getAudioInputStream(Unknown Source) at javax.sound.sampled.AudioSystem.getAudioInputStream(Unknown Source) at com.chrissman.threads.AePlayWave.run(AePlayWave.java:47)
將您的聲音目錄移至項目的根目錄中。 – user1929959