Reputation: 1353
My java code is below.I wrote url=URL(s); but it is not true.I want to make a casting operation to convert a string that is taken from the user ,to an URL.How can I do this operation?Is there any method to do this?
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);
}
Upvotes: 27
Views: 131177
Reputation: 15144
As of Java 20, the URL constructor has been deprecated and developers who still need to use URL are now encouraged to adtop the java.net.URI
class:
If you know the input, you can use the java.net.URI::create
method instead:
URL url = URI.create(s).toURL();
This method works the same behavior as the constructor, with a twist:
This method is provided for use in situations where it is known that the given string is a legal URI, for example for URI constants declared within a program, and so it would be considered a programming error for the string not to parse as such.
Upvotes: 1
Reputation: 1211
You should first convert your string into a URI
, then convert the URI
into a URL
.
For example:
String str = "http://google.com";
URI uri = new URI(str);
URL url = uri.toURL();
Please note, there are 2 unhandled exceptions; so you should wrap the above code within 2 try/catch statements.
Upvotes: 10
Reputation: 171
Use the URL constructor
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);
}
Upvotes: 7
Reputation: 1428
You can't cast String to URL, since String is not a subclass of URL. You can create new instance of URL, passing String as argument to the constructor. In Java, you always invoke constructor using keyword new:
URL url = new URL(string);
Upvotes: 45