什么是URL
URL的全称:Uniform Resource Locator,统一资源定位符。用于描述一个资源在网络中的位置,资源也可在本地。根据访问协议的不同,可以有不同的描述形式:
- http协议:http://www.zhk.me:80/index.php
- ftp协议:ftp://174.123.12.09:28/file/logo.png
- 本地资源:file:/home/admin/Desktop/readme.txt
- 等等
URI和URL关系
URI (Uniform Resource Identifier) 统一资源描述符,一种字符串语义规则,用于描述一个资源的位置。URI是更高层次的描述,URL和URN都是URI的子集。
URL、URI和UR三者之间的区别:http://web.jobbole.com/83452/
Java里的URL
JDK1.0就引入了URL对象:java.net.URL。通过URL字符串,就可以直接生成URL对象。
URL url = new URL("http://zhk.me:80/loginCheck.jsp?userName=alex&pwd=123");
System.out.println("host: " + url.getHost());
System.out.println("port: " + url.getPort());
// host + port = authority
System.out.println("authority: " + url.getAuthority());
System.out.println("path: " + url.getPath());
System.out.println("query: " + url.getQuery());
// path + query = file
System.out.println("file: " + url.getFile());
// Output:
host: zhk.me
port: 80
authority: zhk.me:80
path: /loginCheck.jsp
query: userName=alex&pwd=123
file: /loginCheck.jsp?userName=alex&pwd=123
本地资源URL是以file开头,因为不涉及到query,所以getFile()和getPath()是一样的。
URL url = new URL("file:/home/admin/Desktop/readme.txt");
JavaFX访问整个互联网
JavaFX的初衷是RIA(Rich Internet Application),富互联网应用程序,所以他需要访问的资源需要用URL才能描述,资源可以在互联网上任何一个可以访问的电脑上。例如JavaFX的Image:
// JavaFx cannot find the image if write like this.
Image image1 = new Image("/home/admin/logo.png");
// The input string shall be URL format.
Image image2 = new Image("http://www.images.ne/search/logo23.png");
// Local resource
Image image2 = new Image("file:/home/admin/logo.png");
当使用JavaFX,发现资源访问不到时,首先检查下资源是不是URL的描述格式。
Java类加载器,可以获得资源的URL String,以及资源的InputStream,这样可以方便地加载本地资源。下面是生成Image的例子:
//getResource(...).toString()是调用getResource(...).toExternalForm()生成String
new Image(getClass().getResource("logo.png").toString());
new Image(getClass().getResource("logo.png").toExternalForm());
new Image(getClass().getResourceAsStream("logo.png"));
从File获得URI和URL
File file = ...; URI uri = file.toURI(); URL url = file.toURI().toURL();
从Path获得URI和URL
Path path = Paths.get("../logo.png");
URI uri = path.toUri();
URL url = path.toUri().toURL();
JavaFX读取本地资源
本地资源,如图片、CSS文件等,JavaFX可以通过相对路径或绝对路径访问。
代码中的路径
// Relative path
new Image("images/logo.png");
new Image("../icons/splash.png");
// Absolute path
new Image("file:/home/admin/add.png");
FXML中的路径
// Relative path <Image url="@../images/flower.gif" /> // Absolute path <Image url="file:/C:/Users/Administrator/workspace/src/images/flower.gif" />