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();
}
有帮助吗?

解决方案 2

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 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.

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();
}

Try this

InputStream input = new URL("http://www.somewebsite.com/a.txt").openStream();
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top