Reputation: 955
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?
Upvotes: 14
Views: 15309
Reputation:
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)
Upvotes: 23
Reputation: 162801
No need to special case file URIs. The same code works for either case. I just tested it with the following little scratch program:
import java.io.*;
import java.net.*;
public class URIReadTest {
public static void main(String[] args) throws Exception {
URI uri = new URI("file:///tmp/test.txt");
InputStream in = uri.toURL().openConnection().getInputStream();
// or, more concisely:
// InputStream in = uri.toURL().openStream();
int b;
while((b = in.read()) != -1) {
System.out.print((char) b);
}
in.close();
}
}
Make a /tmp/test.txt
on your system and you'll see the contents of it printed out when you compile and run the above code.
Upvotes: 1
Reputation: 2855
you can check the characters at the start of the string with the startsWith(String prefix) function, it is www. or http:// use the first method otherwise use the second method.
Upvotes: -1