URL.getContent()返回的是一个Object对象,可以用.getClass().getName()获得这个对象实际的名字,如下代码:(这里在创建URL对象的时候,向构造方法里传的值,必须要以http://这个协议开头,要不会抛出异常:java.net.MalformedURLException: no protocol: www.baidu.com)
URL url = new URL("http://www.baidu.com");
Object content = url.getContent();
System.out.println(content.getClass().getName());
以上代码打印的是:
sun.net.www.protocol.http.HttpURLConnection$HttpInputStream
可以利用URL的openConnection方法,返回一个URLConnection对象,此对象可以用来获取输入流。
URL url = new URL("http://www.baidu.com");
URLConnection urlConnection = url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
int c ;
while ((c = inputStream.read()) != -1) {
System.out.println((char)c);
}
inputStream.close();
或者用URL本身的openStream方法获取输入流。
URL url = new URL("http://www.baidu.com");
//打开到此 URL 的连接并返回一个用于从该连接读入的 InputStream。
InputStream in = url.openStream();
int c;
while ((c = in.read()) != -1)
System.out.print(c);
in.close();
利用以下方法可以查看URL支持哪些scheme:
String host = "www.java2s.com";
String file = "/index.html";
String[] schemes = {"http", "https", "ftp", "mailto", "telnet", "file", "ldap", "gopher",
"jdbc", "rmi", "jndi", "jar", "doc", "netdoc", "nfs", "verbatim", "finger", "daytime",
"systemresource"};
for (int i = 0; i < schemes.length; i++) {
try {
URL u = new URL(schemes[i], host, file);
System.out.println(schemes[i] + " is supported/r/n");
} catch (Exception ex) {
System.out.println(schemes[i] + " is not supported/r/n");
}
}
结果为
http is supported/r/n
https is supported/r/n
ftp is supported/r/n
mailto is supported/r/n
telnet is not supported/r/n
file is supported/r/n
ldap is not supported/r/n
gopher is not supported/r/n
jdbc is not supported/r/n
rmi is not supported/r/n
jndi is not supported/r/n
jar is supported/r/n
doc is not supported/r/n
netdoc is supported/r/n
nfs is not supported/r/n
verbatim is not supported/r/n
finger is not supported/r/n
daytime is not supported/r/n
systemresource is not supported/r/n
URL可以用来获取本地的资源文件,如xml,properties,txt等。看到说是总共有4种方法,这里先总结两个常用的,在项目中的用法。
代码结构及资源文件位置:
通过本类的class对象的getResource方法,path不加“/”是从当前目录找,加了是从根目录找。
public static void getResource() throws IOException {
// URL url = GetURLResource.class.getResource("configTmp1.xml");
URL url = GetURLResource.class.getResource("/JavaNet/GetResourceByURL/configTmp1.xml");
InputStream inputStream = url.openStream();
int c ;
while ((c = inputStream.read()) != -1) {
System.out.println((char)c);
}
inputStream.close();
}
以上方法会按字符打印configTmp1.xml的内容
2.通过本类classLoader的getResource方法,这个方法的path不能以"/"开头,相当于每次都从根目录下找。
public static void getResource() throws IOException {
URL url = GetURLResource.class.getClassLoader().getResource("JavaNet/GetResourceByURL/configTmp1.xml");
InputStream inputStream = url.openStream();
int c ;
while ((c = inputStream.read()) != -1) {
System.out.println((char)c);
}
inputStream.close();
}
参考:
http://www.cnblogs.com/alwayswyy/p/6421267.html
转载于:https://blog.51cto.com/10750710/1953584