从uri打开流

MTi*_*ted 15 java uri

我有一个uri(java.net.URI),如http://www.example.com.如何在Java中将其作为流打开?

我真的必须使用URL类吗?

Vij*_*bey 12

您必须创建一个新URL对象,然后在该URL实例上打开流.一个例子如下.

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();
}
Run Code Online (Sandbox Code Playgroud)

  • uri.toURL()没有显示在我的android工作室项目中? (7认同)

Jef*_*rey 5

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

是的,您必须以URL某种方式使用该类.


mar*_*c64 5

您应该使用ContentResolver来获取InputStream:

InputStream is = getContentResolver().openInputStream(uri);
Run Code Online (Sandbox Code Playgroud)

代码在 Activity 对象范围内有效。