20

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?

3
  • Why don't you want to use the URL class?
    – Andy
    Commented May 18, 2012 at 19:29
  • 1
    The problem with URL is that equals and hashcode are blocking operations which does network lookup. Url also seems to be missing a method to normalize a url and convert an relative url to an absolute url.
    – MTilsted
    Commented May 19, 2012 at 4:40
  • 1

5 Answers 5

18

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();
}
3
  • 8
    uri.toURL() is not showing in my android studio project? Commented Sep 14, 2016 at 7:02
  • same uri.toURL() is not showing in my android studio
    – Wardruna
    Commented Sep 19, 2016 at 13:04
  • toURL() does not work on Android because Android uses android.net.Uri, not java.net.URI as referenced in this post. For Android see here.
    – Floern
    Commented Sep 7, 2020 at 13:04
6

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

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

6

You should use ContentResolver to obtain InputStream:

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

Code is valid inside Activity object scope.

3

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

0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.