Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java convert inputStream to URL

How can I convert an inputStream to a URL? Here is my code:

InputStream song1 = this.getClass().getClassLoader().getResourceAsStream("/songs/BrokenAngel.mp3");
URL song1Url = song1.toUrl(); //<- pseudo code
MediaLocator ml = new MediaLocator(song1Url);
Player p;
try {
    p = Manager.createPlayer(ml);
    p.start();
} catch (NoPlayerException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
like image 632
sanchixx Avatar asked Oct 13 '13 17:10

sanchixx


3 Answers

I am not sure you really want to do this. If you need URL for your specific task just do the following:

URL url = this.getClass().getClassLoader().getResource("/songs/BrokenAngel.mp3");

If however you retrieve input stream in one part of you code, then pass it to another module and there want to find what was the source URL for this input stream it is "almost" impossible. The problem is that you get BufferedInputStream that wraps FileInputStream that does not store the information about it source. You cannot retrieve it even using reflection. If you really want to do this you can do the following.

  1. implement you own UrlInputStream extends InputStream the gets into constructor URL, stores it in class varible, creates input stream by invocation of url.openStream() and wraps it.

  2. Now you can use your stream as usual input stream until you have to retrieve the URL. At this point you have to cast it to your UrlInputStream and call getUrl() method that you will implement.

like image 193
AlexR Avatar answered Oct 29 '22 09:10

AlexR


Note that this approach requires the mp3 to be within your application's sub-directory called songs. You can also use relative pathing for the /songs/BrokenAngel.mp3 part (../../ or something like that. But it takes your applications directory as base!

    File appDir = new File(System.getProperty("user.dir"));
    URI uri = new URI(appDir.toURI()+"/songs/BrokenAngel.mp3");
    // just to check if the file exists
    File file = new File(uri);
    System.out.println(file.exists())
    URL song1Url = uri.toURL();
like image 31
Roman Vottner Avatar answered Oct 29 '22 10:10

Roman Vottner


I think what you want is ClassLoader.findResource(String)

That should return a properly formatted jar:// URL. I haven't tested it myself though, so beware

like image 1
torquestomp Avatar answered Oct 29 '22 08:10

torquestomp