Java convert inputStream to URL
Andrew Mclaughlin
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();
} 1 5 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.
implement you own
UrlInputStream extends InputStreamthe gets into constructorURL, stores it in class varible, creates input stream by invocation ofurl.openStream()and wraps it.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
UrlInputStreamand callgetUrl()method that you will implement.
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(); 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
Try this
URI uri = new URI("/songs/BrokenAngel.mp3");
URL song1Url = uri.toURL();
MediaLocator ml = new MediaLocator(song1Url);
Player p;
try { p = Manager.createPlayer(ml); p.start();
} catch (NoPlayerException e) { e.printStackTrace();
} catch (IOException e) { e.printStackTrace();
} 1 Try this
InputStream input = new URL("").openStream();