0

This is a 100% win console application. So here's the problem.

I want to load the file music.xm that I want to place inside the jar. The problem come up when I try to call the file through a relative path. The start directory it's not the Java project one, but my Windows User Folder.

If I call

File music = new File("\\music.xm");


javax.sound.sampled.UnsupportedAudioFileException: /C:/Users/XXXX/Desktop/./music/music.xm

If I call

    File music = new File(".\\music.xm");

I get

    javax.sound.sampled.UnsupportedAudioFileException: /C:/music.xm
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62

1 Answers1

1

If its in your jar, you can use

getclassLoader().getResourceAsStream("music.xm")

You can use this inputStream however you like. But remember, the path should be relative to classpath root of the classloader.

In addition, if you are sure "music.xm" exists as an independent file on filesystem in a fixed relative location to your .class files you can also use :

getclassLoader().getResource("music.xm")

You can look on SO and here for documentation.

Community
  • 1
  • 1
rocketboy
  • 9,573
  • 2
  • 34
  • 36
  • i basically copied the music.xm in all the folder of my netbeans project but i still get a nullpointerexception. String path = FirstBoot.class.getClassLoader().getResource("music.xm").toString(); System.out.print(path); File music = new File(path); – Matteo Raizer Fanciulli Aug 08 '13 at 13:02
  • NPE (most probably) is because of missing resource. The resource will be looked for in your `target` directory where all your compiled code goes. Btw, how are you packaging your jar? – rocketboy Aug 08 '13 at 13:10
  • clean&build in netbeans, nothing particular. And inside the jar the file actually exist. – Matteo Raizer Fanciulli Aug 08 '13 at 13:15
  • Using "music/music.xm" and creating a folder with this name inside the project i get this error: [ModuleFactory] Failed with loading file:/C:/Users\XXXX/Desktop/jar:file:/C:/Users/XXX/Documents/NetBeansProjects/happyh/dist/happyh.jar!/music/music.xm quite a strange path... – Matteo Raizer Fanciulli Aug 08 '13 at 13:18
  • That is because you are trying to access it as a file - `getResource()`. Use `getResourceAsStream()` – rocketboy Aug 08 '13 at 13:23
  • after few workaround i made it! this is the snippet of code to retrieve the url (instead of the file) that i needed. URL resourceUrl = FirstBoot.class.getClassLoader().getResource("music/music.xm"); – Matteo Raizer Fanciulli Aug 08 '13 at 13:34