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

http://somepath.com/mysuperfile.xsl
:

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


or this way if my uri is
file:///somepath/mysuperfile.xsl
:

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
java.nio.*
package?

Answer

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() );
}

http://docs.oracle.com/javase/6/docs/api/java/net/URI.html#getScheme%28%29

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

return myURI.toURL().openStream();

or

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

(as you already did for HTTP protocol/scheme)