I have various urls like this:
String a = "file:./bla/file.txt"; // Valid, see See [RFC 3986][1], path - rootless definition
String b = "file:.file.txt"; // Valid, see See [RFC 3986][1], path - rootless definition
String c = "file:./file.txt"; // Valid, see See [RFC 3986][1], path - rootless definition
String d = "file:///file.txt";
String e = "file:///folder/file.txt";
String f = "http://example.com/file.txt";
String g = "https://example.com/file.txt";
These are all valid URLS, and I can convert them to a URL in java without errors:
URL url = new URL(...);
I want to extract the filename from each of the examples above, so I'm left with just:
file.txt
I have tried the following, but this doesn't work for example b above (which is a valid URL):
b.substring(path.lastIndexOf('/') + 1); // Returns file:.file.txt
I can prob write some custom code to check for slashes, just wondering if there a better more robust way to do it?
The URI class properly parses the parts of a URI. For most URLs, you want the path of the URI. In the case of a URI with no slashes, there won’t be any parsing of the parts, so you’ll have to rely on the entire scheme-specific part:
URI uri = new URI(b);
String path = uri.getPath();
if (path == null) {
path = uri.getSchemeSpecificPart();
}
String filename = path.substring(path.lastIndexOf('/') + 1);
The above should work for all of your URLs.
I have the following strings:
http://somedomain.com/dir/sub/folder/file.txt
OR
https://10.0.0.1/dir/sub/folder/another_folder/file.txt
I want to remove everything before the third forward slash (remove the domain) and still keep the third forward slash.
Expected results:
/dir/sub/folder/file.txt
OR
/dir/sub/folder/another_folder/file.txt
Uri uri = Uri.parse("https://graph.facebook.com/me/home?limit=25&since=1374196005");
String protocol = uri.getScheme();
String server = uri.getAuthority();
String path = uri.getPath();
Set<String> args = uri.getQueryParameterNames();
String limit = uri.getQueryParameter("limit");
I think you need a path value
You can use the URL class that is what you are looking for.
The URL class provides several methods that let you query URL objects. You can get the protocol, authority, host name, port number, path, query, filename, and reference from a URL using these accessor methods
Use this :
URL aURL = new URL("https://10.0.0.1/dir/sub/folder/another_folder/file.txt");
aUrl.getPath();
Output result
path = /dir/sub/folder/another_folder/file.txt
I have a program which requires path to a file. Currently, it's configured like this:
public class Main {
private static final String ACOUSTIC_MODEL_PATH =
"resource:/edu/cmu/sphinx/models/en-us/en-us";
private static final String DICTIONARY_PATH =
"resource:/edu/cmu/sphinx/models/en-us/cmudict-en-us.dict";
I have two questions:
What is this resource:/path/goes/here format, spefically resource word?
How do I specify path to a file on a disk?
I tried these options but file fails to be found:
private static final String DICTIONARY_PATH = "/d/cmudict-en-us.dict";
private static final String DICTIONARY_PATH = "file:/d/cmudict-en-us.dict";
private static final String DICTIONARY_PATH = "file://d/cmudict-en-us.dict";
Here is how supposedly the path is used (location is path here):
public static URL resourceToURL(String location) throws MalformedURLException {
Matcher jarMatcher = jarPattern.matcher(location);
if (jarMatcher.matches()) {
String resourceName = jarMatcher.group(1);
return ConfigurationManagerUtils.class.getResource(resourceName);
} else {
if (location.indexOf(':') == -1) {
location = "file:" + location;
}
return new URL(location);
}
}
Seems that resources:/ is just an internal pattern which is used in your program (see jarPattern regular expression which should be declared somewhere in your program). It's not a common syntax of describing the URLs. But if this pattern does not match, the fallback implementation is to treat the string as the URL. Local file URLs are always started with file:/// followed by normal path where backslashes are replaced with forward slashes.
Try the following string, it's a valid URL:
"file:///d:/cmudict-en-us.dict"
If you want to specify a path on a disk, you can use its absolute path like so:
String path = "C:\Folder\AnotherFolder\file.txt";
The problem with this, however, is that the '\' symbol can cause issues as java recognizes it as trying to mark an escape sequence like \n, \r, etc. To prevent this error, you can replace '\' with '\\' and the JVM will read it as a regular path. So instead of the code above, you can try this :
String path = "C:\\Folder\\AnotherFolder\\file.txt";
I'm trying to URIENcode a string in java using URIUtils of spring framework.
it supposed to be simple as far as I understood but for some reason the string stays unchanged.
I have the following string:
http://www.foo.bar/foo/bar
and I want to URIEncode it.
final String ENC = "UTF-8";
String uri = "http://www.foo.bar/foo/bar";
final String result = UriUtils.encodeFragment(uri, ENC);
the result is the same string not encoded.
what am I doing wrong?
how can I properly URIEncode that string in order to use it in get parameters ?
I don't want to use a URLBuilder because i need to use the resulted output and create a hash table for an internal database.
thank you
I think you can achieve the same using java.net.URLEncoder, avoiding the spring class
System.out.println(URLEncoder.encode("http://www.foo.bar/foo/bar", "UTF-8"))
would print
http%3A%2F%2Fwww.foo.bar%2Ffoo%2Fbar
There is an RFC which allows URI building from different parameters: URI templates.
Since you use Java, there happens to be an implementation available (disclaimer: yes it's mine).
You could then do like this:
// The template
final URITemplate tmpl = new URITemplate("http://my.site/foo{?params*}");
// The query parameters
// Uses Maps from Guava since the lib depends on it
final Map<String, String> params = Maps.newHashMap();
params.put("site", "http://www.foo.bar/foo/bar");
// The template data expansion
final Map<String, VariableValue> data = Maps.newHashMap();
data.put("params", new MapValue(params));
// Expand, build the URL
// The expansion takes care of all the encoding for you
final URL url = new URL(template.expand(data));
I am trying to get a java.net.URI object from a String. The string has some characters which will need to be replaced by their percentage escape sequences. But when I use URLEncoder to encode the String with UTF-8 encoding, even the / are replaced with their escape sequences.
How can I get a valid encoded URL from a String object?
http://www.google.com?q=a b gives http%3A%2F%2www.google.com... whereas I want the output to be http://www.google.com?q=a%20b
Can someone please tell me how to achieve this.
I am trying to do this in an Android app. So I have access to a limited number of libraries.
You might try: org.apache.commons.httpclient.util.URIUtil.encodeQuery in Apache commons-httpclient project
Like this (see URIUtil):
URIUtil.encodeQuery("http://www.google.com?q=a b")
will become:
http://www.google.com?q=a%20b
You can of course do it yourself, but URI parsing can get pretty messy...
Android has always had the Uri class as part of the SDK:
http://developer.android.com/reference/android/net/Uri.html
You can simply do something like:
String requestURL = String.format("http://www.example.com/?a=%s&b=%s", Uri.encode("foo bar"), Uri.encode("100% fubar'd"));
I'm going to add one suggestion here aimed at Android users. You can do this which avoids having to get any external libraries. Also, all the search/replace characters solutions suggested in some of the answers above are perilous and should be avoided.
Give this a try:
String urlStr = "http://abc.dev.domain.com/0007AC/ads/800x480 15sec h.264.mp4";
URL url = new URL(urlStr);
URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
url = uri.toURL();
You can see that in this particular URL, I need to have those spaces encoded so that I can use it for a request.
This takes advantage of a couple features available to you in Android classes. First, the URL class can break a url into its proper components so there is no need for you to do any string search/replace work. Secondly, this approach takes advantage of the URI class feature of properly escaping components when you construct a URI via components rather than from a single string.
The beauty of this approach is that you can take any valid url string and have it work without needing any special knowledge of it yourself.
Even if this is an old post with an already accepted answer, I post my alternative answer because it works well for the present issue and it seems nobody mentioned this method.
With the java.net.URI library:
URI uri = URI.create(URLString);
And if you want a URL-formatted string corresponding to it:
String validURLString = uri.toASCIIString();
Unlike many other methods (e.g. java.net.URLEncoder) this one replaces only unsafe ASCII characters (like ç, é...).
In the above example, if URLString is the following String:
"http://www.domain.com/façon+word"
the resulting validURLString will be:
"http://www.domain.com/fa%C3%A7on+word"
which is a well-formatted URL.
If you don't like libraries, how about this?
Note that you should not use this function on the whole URL, instead you should use this on the components...e.g. just the "a b" component, as you build up the URL - otherwise the computer won't know what characters are supposed to have a special meaning and which ones are supposed to have a literal meaning.
/** Converts a string into something you can safely insert into a URL. */
public static String encodeURIcomponent(String s)
{
StringBuilder o = new StringBuilder();
for (char ch : s.toCharArray()) {
if (isUnsafe(ch)) {
o.append('%');
o.append(toHex(ch / 16));
o.append(toHex(ch % 16));
}
else o.append(ch);
}
return o.toString();
}
private static char toHex(int ch)
{
return (char)(ch < 10 ? '0' + ch : 'A' + ch - 10);
}
private static boolean isUnsafe(char ch)
{
if (ch > 128 || ch < 0)
return true;
return " %$&+,/:;=?#<>#%".indexOf(ch) >= 0;
}
You can use the multi-argument constructors of the URI class. From the URI javadoc:
The multi-argument constructors quote illegal characters as required by the components in which they appear. The percent character ('%') is always quoted by these constructors. Any other characters are preserved.
So if you use
URI uri = new URI("http", "www.google.com?q=a b");
Then you get http:www.google.com?q=a%20b which isn't quite right, but it's a little closer.
If you know that your string will not have URL fragments (e.g. http://example.com/page#anchor), then you can use the following code to get what you want:
String s = "http://www.google.com?q=a b";
String[] parts = s.split(":",2);
URI uri = new URI(parts[0], parts[1], null);
To be safe, you should scan the string for # characters, but this should get you started.
I had similar problems for one of my projects to create a URI object from a string. I couldn't find any clean solution either. Here's what I came up with :
public static URI encodeURL(String url) throws MalformedURLException, URISyntaxException
{
URI uriFormatted = null;
URL urlLink = new URL(url);
uriFormatted = new URI("http", urlLink.getHost(), urlLink.getPath(), urlLink.getQuery(), urlLink.getRef());
return uriFormatted;
}
You can use the following URI constructor instead to specify a port if needed:
URI uri = new URI(scheme, userInfo, host, port, path, query, fragment);
Well I tried using
String converted = URLDecoder.decode("toconvert","UTF-8");
I hope this is what you were actually looking for?
The java.net blog had a class the other day that might have done what you want (but it is down right now so I cannot check).
This code here could probably be modified to do what you want:
http://svn.apache.org/repos/asf/incubator/shindig/trunk/java/common/src/main/java/org/apache/shindig/common/uri/UriBuilder.java
Here is the one I was thinking of from java.net: https://urlencodedquerystring.dev.java.net/
Or perhaps you could use this class:
http://developer.android.com/reference/java/net/URLEncoder.html
Which is present in Android since API level 1.
Annoyingly however, it treats spaces specially (replacing them with + instead of %20). To get round this we simply use this fragment:
URLEncoder.encode(value, "UTF-8").replace("+", "%20");
I ended up using the httpclient-4.3.6:
import org.apache.http.client.utils.URIBuilder;
public static void main (String [] args) {
URIBuilder uri = new URIBuilder();
uri.setScheme("http")
.setHost("www.example.com")
.setPath("/somepage.php")
.setParameter("username", "Hello Günter")
.setParameter("p1", "parameter 1");
System.out.println(uri.toString());
}
Output will be:
http://www.example.com/somepage.php?username=Hello+G%C3%BCnter&p1=paramter+1