Open stream from uri

对着背影说爱祢 提交于 2019-12-23 06:57:17

问题


I got an uri (java.net.URI) such as http://www.example.com. How do I open it as a stream in Java?

Do I really have to use the URL class instead?


回答1:


You will have to create a new URL object and then open stream on the URL instance. An example is below.

try {

   URL url = uri.toURL(); //get URL from your uri object
   InputStream stream = url.openStream();

} catch (MalformedURLException e) {
   e.printStackTrace();
} catch (URISyntaxException e) {
   e.printStackTrace();
}catch (IOException e) {
   e.printStackTrace();
}



回答2:


URLConnection connection = uri.toURL().openConnection()

Yes, you have to use the URL class in one way or the other.




回答3:


uri.toURL().openStream() or uri.toURL().openConnection().getInputStream()




回答4:


You can use URLConnection to read data for given URL. - URLConnection




回答5:


You should use ContentResolver to obtain InputStream:

InputStream is = getContentResolver().openInputStream(uri);

Code is valid inside Activity object scope.



来源:https://stackoverflow.com/questions/10657687/open-stream-from-uri

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!