1

Is there a method which would accept the following paths and return appropriate URI:

test.xml // File in CWD
./test.xml // The same
../test.xml // File in parent directory
/etc/test.xml // Absolute path
file:///etc/test.xml // Full URL
http://example.com/test.xml // URL for http

Currently all I can think of is parse as url (URL.create) and if it fails attempt to try to parse it as File/Path.

3 Answers 3

1

If you want to use those URIs, for example in File constructor, you need to specify base URI for relative paths. You can do it with URI.resolve.

URI basePath = new URI("file:///base_dir/");
URI uri = basePath.resolve("foo.txt");

System.out.println(new File(uri));
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I've tried using URI.resolve but I've mixed the this/argument.
1

Use URI, not URL.

This may or may not be what you actually want, however, depending on what you need to do with the result.

Comments

1

You can create an URI for each of the resources you pointed as follows:

public class T {

    public static void main(final String[] args) throws URISyntaxException {
        System.out.println(new URI("test.xml"));
        System.out.println(new URI("./test.xml"));
        System.out.println(new URI("../test.xml"));
        System.out.println(new URI("/etc/test.xml"));
        System.out.println(new URI("file:///etc/test.xml"));
        System.out.println(new URI("http://example.com/test.xml"));

    }

}

Additionally, you can retrieve the URL with the method "toURL()", but this just in case of the URI is absolute.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.