M314 M314 - 3 months ago 7
Java Question

find protocol corresponding to URI in Java

I have URI object in Java. I want to convert it to InputStream, but the conversion should depend on the protocol. I can make it this way if my URI is


return myURI.toURL().openConnection().getInputStream();

or this way if my uri is

return new FileInputStream(Paths.get(myURI).toFile());

or maybe even some another way. I can try to check it manually, but do Java have some nice/proper way to check it, maybe using that new


Every URI is defined as consisting of four parts, as follows:

[scheme name] : [hierarchical part] [[ ? query ]] [[ # fragment ]]

If the thing you want is the scheme name (which roughly translates to protocol), just use

switch ( myURI.getScheme() ) {
  case "http":
    return myURI.toURL().openConnection().getInputStream();
  case "ftp":
    // do something   
  case "file":
    return new FileInputStream( Paths.get(myURI).toFile() );


or, if you just want to generate an InputStream without differentiating the scheme, simply use

return myURI.toURL().openStream();


return myURI.toURL().openConnection().getInputStream();

(as you already did for HTTP protocol/scheme)