Java File Path Create buildPath(String part1, String part2)

Here you can find the source of buildPath(String part1, String part2)

Description

Takes two strings as input and builds a valid path out of them by placing a slash inbetween them.

License

Open Source License

Parameter

Parameter Description
part1 The first part of the path
part2 The second part of the path

Return

The combination of part1 and part2. Example 1: If given input: part1 = "/home/user" part2 = "subdir1/subdir2/file.txt" output would be: "/home/user/file/subdir1/subdir2/file.txt" Notice the addition of a slash between the two strings. Example 2: If given input: part1 = "/home/user/" part2 = "/subdir1/subdir2/file.txt" output would be: "/home/user/subdir1/subdir2/file.txt" Notice the removal of a slash between the two strings.

Declaration

public static String buildPath(String part1, String part2) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /**/*from w w  w. j a  v a 2  s  .  co  m*/
     * Takes two strings as input and builds a valid path out of them by placing a slash inbetween them.
     * This method assumes a unix-type file system and uses forward slashes.
     * @param part1 The first part of the path
     * @param part2 The second part of the path
     * @return The combination of part1 and part2.
     * Example 1:
     * If given input:
     *   part1 = "/home/user"
     *   part2 = "subdir1/subdir2/file.txt"
     * output would be: "/home/user/file/subdir1/subdir2/file.txt"
     * Notice the addition of a slash between the two strings.
     * Example 2:
     * If given input:
     *   part1 = "/home/user/"
     *   part2 = "/subdir1/subdir2/file.txt"
     * output would be: "/home/user/subdir1/subdir2/file.txt"
     * Notice the removal of a slash between the two strings.
     */
    public static String buildPath(String part1, String part2) {
        String retVal;
        if (part1.endsWith("/") && part2.startsWith("/")) {
            part1 = part1.substring(0, part1.length() - 1);
            retVal = part1 + part2;
        } else if (!part1.endsWith("/") && !part2.startsWith("/")) {
            retVal = part1 + "/" + part2;
        } else
            retVal = part1 + part2;
        return retVal;
    }
}

Related

  1. buildPath(final String basePath, final String path)
  2. buildPath(final String... tokens)
  3. buildPath(Integer sAccountId, String objectPath)
  4. buildPath(long id, boolean justDir)
  5. buildPath(String first, String... parts)
  6. buildPath(String path, String file)
  7. buildPath(String... paths)
  8. buildPath(String... strings)
  9. buildPath(String[] seperatedName)