java url 字符串_Java程序检查字符串中的URL

可以创建一个程序来检查字符串是否为正确的URL。URL的示例如下所示-String = https://www.wikipedia.org/

The above string is a valid URL

演示该程序的程序如下。

示例import java.net.URL;

public class Example {

public static boolean check_URL(String str) {

try {

new URL(str).toURI();

return true;

}catch (Exception e) {

return false;

}

}

public static void main(String[] args) {

String str = "http://www.wikipedia.org/";

System.out.println("String = " + str);

if (check_URL(str))

System.out.println("The above string is a URL");

else

System.out.println("The above string is not a URL");

}

}

输出结果String = http://www.wikipedia.org/

The above string is a URL

现在让我们了解上面的程序。

在函数check_URL()中,创建一个URL对象。如果在创建对象时没有异常,则返回true。否则,返回false。演示此过程的代码段如下所示。public static boolean check_URL(String str) {

try {

new URL(str).toURI();

return true;

}catch (Exception e) {

return false;

}

}

在函数中main(),字符串被打印出来。然后使用字符串str调用函数check_URL()。如果返回true,则str是URL并被打印,否则str不是URL并被打印。演示此过程的代码段如下所示。public static void main(String[] args) {

String str = "http://www.wikipedia.org/";

System.out.println("String = " + str);

if (check_URL(str))

System.out.println("The above string is a URL");

else

System.out.println("The above string is not a URL");

}


版权声明:本文为weixin_39616674原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。