Java URI toURI()方法及示例

来源:这里教程网 时间:2026-02-17 21:16:05 作者:

Java URI toURI()方法及示例

URL类的 getURI() 函数将URL对象转换为URI对象。任何符合RFC2396的URL都可以被转换为URI。如果转换为URI格式,不符合指定格式的URL将产生一个错误。

函数签名

public URI toURI()

语法

url.toURI()

参数。这个方法不接受任何参数。

返回类型 :该函数返回一个由该URL对象转换而来的 URI对象

异常 :如果这个URL没有严格按照RFC2396的格式化,不能被转换为URI,这个函数会抛出URISyntaxException。

下面的例子将说明toURI()函数的使用。

例1 :

// Java program to convert URL to URI  import java.net.*;  class GFG {    public static void main(String args[])    {          // url and uri objects        URL url = null;        URI uri = null;          try {              // create a URL            url = new URL("https://www.geeksforgeeks.org");              // display the URL            System.out.println("URL: " + url);              // convert the URL to URI            uri = url.toURI();              // display the URI            System.out.println("URI: " + uri);        }        // if any error occurs        catch (Exception e) {              // display the error            System.out.println(e);        }    }}

输出:

URL: https://www.geeksforgeeks.orgURI: https://www.geeksforgeeks.org

例2 :

// Java program to convert URL to URI  import java.net.*;  class GFG {    public static void main(String args[])    {          // url and uri objects        URL url = null;        URI uri = null;          try {              // create an invalid URL            url = new URL("https://www.geeksfor>geeks.com");              // display the URL            System.out.println("URL: " + url);              // convert the URL to URI            uri = url.toURI();              // display the URI            System.out.println("URI: " + uri);        }        // if any error occurs        catch (Exception e) {              // display the error            System.out.println(e);        }    }}

输出:

URL: https:// www.geeksfor>geeks.comjava.net.URISyntaxException: Illegal character in authority at index 8: https:// www.geeksfor>geeks.com

相关推荐