如何将inputStream转换为URL?这是我的代码:
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();
}
发布于 2013-10-13 19:19:18
请注意,这种方法要求mp3位于应用程序的子目录中,名为歌。您还可以对/songs/BrokenAngel.mp3
部件(../../或类似的东西)使用相对擦除。但是它以您的应用程序目录为基础!
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();
发布于 2013-10-13 18:27:27
我不确定你真的想这么做。如果您需要用于特定任务的URL,只需执行以下操作:
URL url = this.getClass().getClassLoader().getResource("/songs/BrokenAngel.mp3");
但是,如果您在代码的一部分中检索输入流,那么将其传递到另一个模块,并且需要找到这个输入流的源URL --这“几乎”不可能。问题是,您得到的BufferedInputStream
包的FileInputStream
不存储有关它的信息来源。即使使用反射,也无法检索它。如果你真的想这样做,你可以做以下工作。
UrlInputStream extends InputStream
-- gets进入构造函数URL
,将其存储在varible类中,通过调用url.openStream()
创建输入流并包装它。UrlInputStream
,并调用您将要实现的getUrl()
方法。发布于 2013-10-13 18:16:16
我想你想要的是ClassLoader.findResource(字符串)
它应该返回一个正确格式化的jar:// URL。不过,我还没有亲自测试过,所以要小心
https://stackoverflow.com/questions/19348390
复制相似问题