Java Path Normalize normalizePath(String pathFragment)

Here you can find the source of normalizePath(String pathFragment)

Description

Normalizes the input path to an absolute path prepending / and ensuring that the path does not end in /.

License

Apache License

Parameter

Parameter Description
pathFragment the path.

Return

a normalized path.

Declaration

public static String normalizePath(String pathFragment) 

Method Source Code

//package com.java2s;
/*//from w  w  w  . j ava  2  s  .  c o m
 * Licensed to the Sakai Foundation (SF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The SF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 */

public class Main {
    /**
     * Normalizes the input path to an absolute path prepending / and ensuring that the path
     * does not end in /.
     *
     * @param pathFragment
     *          the path.
     * @return a normalized path.
     */
    public static String normalizePath(String pathFragment) {
        char[] source = pathFragment.toCharArray();
        char[] normalized = new char[source.length + 1];
        int i = 0;
        int j = 0;
        if (source[i] != '/') {
            normalized[j++] = '/';
        }
        boolean slash = false;
        for (; i < source.length; i++) {
            char c = source[i];
            switch (c) {
            case '/':
                if (!slash) {
                    normalized[j++] = c;
                }
                slash = true;
                break;
            default:
                slash = false;
                normalized[j++] = c;
                break;
            }
        }
        if (j > 1 && normalized[j - 1] == '/') {
            j--;
        }
        return new String(normalized, 0, j);
    }
}

Related

  1. normalizePath(String path)
  2. normalizePath(String path)
  3. normalizePath(String path, char sep)
  4. normalizePath(String path, String oldFileSeperator, String newFileSeparator)
  5. normalizePath(String path, String separator)
  6. normalizePath(String pathname)
  7. normalizePathElement(String name)
  8. normalizePathname(String pathname)
  9. normalizePathPart(final String path)