简体   繁体   中英

getClass().getClassLoader().getResource(path) always return null, even when the path is correct

I am using Java project to do this not a dynamic web project and I just placed my .wav file to directly project(on project name right click n paste).

I tried to read many posts but of no use. help me on this. I tried to read many posts but of no use.

try{
      // Open an audio input stream.
      URL url = this.getClass().getClassLoader().getResource("Rain.wav");
      System.out.println("url:"+url);
      AudioInputStream audioIn = AudioSystem.getAudioInputStream(url);
      // Get a sound clip resource.
      Clip clip = AudioSystem.getClip();
      clip.open(audioIn);
      clip.start();
      /* clip.loop(Clip.LOOP_CONTINUOUSLY);  */
 } catch (UnsupportedAudioFileException e) {
      e.printStackTrace();
 }

getClass().getClassLoader().getResource(path) always return null, even when the path is correct

No it doesn't.

I just placed my .wav file to directly project

Exactly. That's the wrong place. Your path isn't correct. Your Rain.wav file needs to be in the root directory of your JAR file the way you're looking for it. The root of the project has precisely nothing to do with it.

Load file from Spring Boot JAR

If you would like to load a file from classpath in a Spring Boot JAR, then you have to use the resource.getInputStream() method to retrieve it as a InputStream. If you try to use resource.getFile() you will receive an error, because Spring tries to access a file system path, but it can not access a path in your JAR.

Resource resource = resourceLoader.getResource("classpath:GeoLite2-Country.mmdb"); InputStream dbAsStream = resource.getInputStream()

[blog] : https://smarterco.de/java-load-file-from-classpath-in-spring-boot/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM