Reputation: 9548
I'm trying to load a .wav file into the memory, but It keep telling me that the file doesn't exists.
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;
}
}
Console:
Wave file not found: java.io.FileInputStream@dd5b524
Wave file notfound: java.io.FileInputStream@570add96
The file is in the package folder. It's in
myPackage/sounds/write.wav
EDIT:
Actually I want to load the sound:
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;
}
But the console is still with error:
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)
Upvotes: 0
Views: 3970
Reputation: 2066
in.toString()
does not return the path used to open the stream, it returns the class name followed by the hash: java.io.FileInputStream@dd5b524
.
The error is because you do not have a file named java.io.FileInputStream@dd5b524
in your current directory.
Since you got an object instead of null
as in
it found your file. You can not use a File
object to get this file, but you have access to it via the in
object. Read the contents from the stream and use it.
Upvotes: 1
Reputation: 5103
Resources can be looked up both with a absolute and relative path. What you currently have is an absolute path starting with /
. So change it into /myPackage/sounds/write.wav
. In general I prefer absolute paths as it can be quite hard to determine which package is the "current" with relative paths.
Upvotes: 0