2

It's a bit confusing with URL and URI. In my project there is a package "sounds" with a .wav file in it. I want to play it via JavaFX MediaPlayer which takes a Media instance. The constructor of Media needs an URI. First I wrote

Media audio = new Media(new File("sounds/my audio.wav").toURI().toString());

But it only works while starting the program through the IDE. When I export my project as an executable JAR it doesn't work anymore, because it is trying to load the file from the direction where the JAR is lying. It should load it from the package instead which was exported into the JAR. I want it to load from the package so I need ClassLoader but it creates an URL. I could write

Media audio = null;
try
{
    audio = new Media(ClassLoader.getSystemResource("sounds/my audio.wav").toURI().toString());
}
catch (URISyntaxException ex)
{
    ex.printStackTrace();
}

That's neither beautiful nor convenient. Unfortunately it has this checked exception... And I would like to create the Media variable as a constant in an interface, where I can't even use try-catch.

So how do I have to write it? Just want to get my file in one line.

Arceus
  • 520
  • 6
  • 16

1 Answers1

4

If it's part of your project, it's not a file (consider what happens when you deploy your application as a jar archive); it's a resource. So you shouldn't include any whitespace in the resource name - each component of the resource name (except for an extension on the last component) should be a valid Java variable name. After renaming, you should load it with something like

Media audio = new Media(getClass().getClassLoader().getResource("sounds/myAudio.wav").toExternalForm());

You can see an "official" Oracle description of resource naming and access here.

James_D
  • 201,275
  • 16
  • 291
  • 322
  • The medthod toExternalForm() is from class URL instead of URI, so I don't know why it's working but it is working.The audio is a ressource per definition, right, but to me it's still a file and neither whitespace nor valid special characters cause any exception, so I leave it. – Arceus Feb 02 '16 at 19:27
  • Ok, it does not work if I use it as runnable jar, still only when starting from IDE. Even if I keep conventions. I get an UnsupportedOperationException: Unsupported protocol "rsrc". If I print out the URL starting by IDE it says something like "file:/C:/projects/projectName/sounds/myAudio.wav". But as jar the URL is printed as "rsrc:sounds/myAudio.wav". – Arceus Feb 02 '16 at 19:55
  • Not sure why you are getting the `rsrc:` protocol on the URL; you should see a `jar:` protocol. Try the updated version (with `getClassLoader()`). – James_D Feb 02 '16 at 20:12
  • But it works with _new Media(ClassLoader.getSystemResource("sounds/myAudio.wav").toExternalForm())_ – Arceus Feb 02 '16 at 20:13
  • This works. It should be marked as the solution. – Phil Mar 31 '23 at 23:34