Java Path Normalize normalizeToDir(CharSequence path)

Here you can find the source of normalizeToDir(CharSequence path)

Description

If: We're at the top of the tree don't remove parent file name.

License

Apache License

Parameter

Parameter Description
path the path to normalize

Return

the normalized path

Declaration

public static StringBuilder normalizeToDir(CharSequence path) 

Method Source Code

//package com.java2s;
/*/* w  w  w .ja  v  a  2 s  . c o  m*/
 * Copyright [2013] PurePerfect.com Licensed 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 {
    /**
     * If: We're at the top of the tree don't remove parent file name. Instead
     * just put in the '/' to prefix the absolute path so that file:
     * 
     * 'myfile.txt' becomes '/' instead.
     * 
     * Else: remove trailing file so that we have the directory name:
     * 
     * 'myfolder/myfile.txt becomes 'myfolder/'.
     * 
     * @param path
     *            the path to normalize
     * @return the normalized path
     */
    public static StringBuilder normalizeToDir(CharSequence path) {
        StringBuilder results = new StringBuilder(path);

        if (!isDirectory(results.toString())) {
            int lastDir = results.lastIndexOf("/");

            if (lastDir < 0) {
                results = new StringBuilder("/");
            } else {
                results.replace(lastDir, path.length(), "/");
            }
        }

        return results;
    }

    /**
     * Whether or not it ends with '/'.
     * 
     * @param classpath
     *            the classpath to test
     * @return Whether or not it ends with '/'.
     */
    public static boolean isDirectory(String classpath) {
        return classpath.endsWith("/");
    }
}

Related

  1. normalizeRegex(String pathPattern)
  2. normalizeResourcesPath(final String path)
  3. normalizeRootPath(String rootPath)
  4. normalizeSlashes(final String path)
  5. normalizeSlashes(String path)
  6. normalizeURI(String prefix, String relativePath)
  7. normalizeUriPath(String path)
  8. normalizeUrlPath(String name)
  9. normalizeUrlPath(String protocol, String host, int portNumber, String basePath)