我的java代码如下。我写了 url=URL(s);但事实并非如此。我想进行强制转换操作,将从用户处获取的字符串转换为 URL。我该如何执行此操作?有什么方法可以执行此操作吗?
public static void main(String[] args) {
System.out.println("Welcome to Download Manager");
URL url;
String s;
Scanner scan= new Scanner(System.in);
s=scan.nextLine();
url=URL(s);
Download download=new Download(url);
}
不能将 String 转换为 URL,因为 String 不是 URL 的子类。您可以创建 URL 的新实例,将 String 作为参数传递给构造函数。在 Java 中,您总是使用关键字 new:
调用构造函数URL url = new URL(string);
使用 URL 构造函数:
url = new URL(s);
使用 URL 构造函数
public static void main(String[] args) {
System.out.println("Welcome to Download Manager");
URL url;
String s;
Scanner scan= new Scanner(System.in);
s=scan.nextLine();
url= new URL(s);
Download download=new Download(url);
}
您应该首先将字符串转换为
URI
,然后将 URI
转换为 URL
。
例如:
String str = "http://google.com";
URI uri = new URI(str);
URL url = uri.toURL();
请注意,有2个未处理的异常;所以你应该将上面的代码包装在 2 个 try/catch 语句中。
您需要将其更改为
url= new URL(s);
从 Java 20 开始,URL 构造函数已被弃用,现在鼓励仍然需要使用 URL 的开发人员添加
java.net.URI
类:
java.net.URI::create
方法代替:
URL url = URI.create(s).toURL();
此方法的行为与构造函数相同,但有一点不同:
此方法适用于已知给定字符串是合法 URI 的情况,例如程序中声明的 URI 常量,因此不解析字符串将被视为编程错误。