-1

I want to create URL using : existing url and 2 strings

I found

Create URL from a String
and
File.separator or File.pathSeparator

but I want to create it without typing '/'

String part1 = "txt1";

String part2 = "txt2";

URL urlBase = new URL(some adress);

now I can write

URL urlNew = urlBase.toURI().resolve(part1).toURL();

but how to add part2 goal is to get adress/txt1/txt2

Community
  • 1
  • 1

2 Answers2

0

Will this help?

public static void main(String[] args) throws MalformedURLException {
        URL domain = new URL("http://google.com");
        URL url = new URL(domain, "test");
        System.out.println(url.toString());
    }

Or

public static void main(String[] args) throws MalformedURLException {
        URL domain = new URL("http://google.com/sample/text/a");
        URL url = new URL(domain, "test");
        System.out.println(url.toString());
    }

Notice that it will add the string to your domain.

Soley
  • 1,716
  • 1
  • 19
  • 33
  • Thanks for reply, result : http://google.com/sample/text/test, but I want to get http://google.com/sample/text/a/test. 'Cruncher' solution is correct but it involves usage of '/' that like I wrote I'm trying to avoid (assumption: we can do this without typing '/') – Arkadiusz Eric Jul 15 '14 at 19:26
0

What about this?

public static void main(String[] args) throws Exception {
    URL urlBase = new URL("http://google.com/2");
    String part1 = "test1/3";
    String part2 = "test2";
    System.out.println(
            urlBase.toString()
            + new URL(urlBase, part1).getPath()
            + new URL(urlBase, part2).getPath()
        );
}

No character is required :)

If you have an empty string, it won't work, so this is the solution for it:

public static void main(String[] args) throws Exception {
        URL urlBase = new URL("http://google.com/2");
        String part1 = "test1/3";
        String part2 = "test2";
        System.out.println(
                urlBase.toString()
                + (part1.isEmpty() ? "" : new URL(urlBase, part1).getPath())
                + (part2.isEmpty() ? "" : new URL(urlBase, part2).getPath())
            );
    }
Soley
  • 1,716
  • 1
  • 19
  • 33