How do i convert String www.mywebsite.com/firefox.txt
to URL ? I wanted to use this in the file object and then into the FileReader
constructor.
A URI is a string containing characters that identify a physical or logical resource.
It is an immutable one-to-one mapping to a resource or data. The method Uri. parse creates a new Uri object from a properly formated String .
You can use the new URI(string)
constructor (for an URI) and the new URL(string)
constructor for a URL
.
But that won't work with a FileReader
- it requires the URI scheme to be file:
If you want to read a remote file, you need something like:
Reader reader = new InputStreamReader(new URL(urlString).openStream(), encoding);
The encoding can be taken from HttpURLConnection
obtained by url.openConnection()
, but you can also set it to something specific if you know it in advance. (Btw, In the above example I've omitted all I/O resource management)
Note (thanks to @StephenC): the url string must be a valid URL, which means it must start with http://
If your goal is to turn that string is to turn that string (and similar ones) into syntactically valid URLs ... like a typical browser's URL bar does ... then the answer is "use heuristics".
Specifically, you will need to figure out what heuristics are most likely to turn the user's input into the URL that the user meant. Then write some code to implement them. I'd start by doing some experiments with a browser whose behavior you like and try to figure out what it is doing.
Your comment is unclear, but I think you are saying that the string is a local file name and you want to turn it into "file:" URL.
File file = new File("www.mywebsite.com/firefox.txt");
URL url = file.toURI().toURL();
If you want to write to a remote file, you can't do that simply using URL object and openStream()
. Writing to remote resources identified by URLs typically requires an http or ftp URL, and use of libraries that implement the respective protocol stack.
Similarly, you can't do it withe the FileWriter API ... unless the file lives in a file system that has been mounted; e.g. as an Windows network share. The FileWriter API only works for files in the unified "file system" that the local operating system makes available to your application.
Finally, we get back to the fact that you need to use a valid URL ... not just the syntactically invalid nonsense that most users type into a browser's URL bar.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With