Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting string to URI

Tags:

java

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.

like image 356
program-o-steve Avatar asked Oct 29 '11 14:10

program-o-steve


People also ask

Is Uri a string?

A URI is a string containing characters that identify a physical or logical resource.

What is Uri parse in android studio?

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 .


2 Answers

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://

like image 192
Bozho Avatar answered Sep 30 '22 09:09

Bozho


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.

like image 23
Stephen C Avatar answered Sep 30 '22 11:09

Stephen C