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