我的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);
}
Run Code Online (Sandbox Code Playgroud)
Grz*_*ski 33
您不能将String强制转换为URL,因为String不是URL的子类.您可以创建URL的新实例,将String作为参数传递给构造函数.在Java中,您始终使用关键字new调用构造函数:
URL url = new URL(string);
Run Code Online (Sandbox Code Playgroud)
您应该首先将字符串转换为 a URI,然后将其转换URI为 a URL。
例如:
String str = "http://google.com";
URI uri = new URI(str);
URL url = uri.toURL();
Run Code Online (Sandbox Code Playgroud)
请注意,有 2 个未处理的异常;所以你应该将上面的代码包装在 2 个 try/catch 语句中。
小智 6
使用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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
73577 次 |
| 最近记录: |