Java Path Is Absolute isAbsolute(String path)

Here you can find the source of isAbsolute(String path)

Description

Whether the path is absolute (starts with a slash) or not.

License

Apache License

Parameter

Parameter Description
path the path

Return

true if it starts with a slash

Declaration

public static boolean isAbsolute(String path) 

Method Source Code

//package com.java2s;
/*/*from ww w . ja  va2 s . c om*/
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF 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 {
    /**
     * Whether the path is absolute (starts with a slash) or not.
     *
     * @param path the path
     * @return true if it starts with a slash
     */
    public static boolean isAbsolute(String path) {
        assert isValid(path);

        return isAbsolutePath(path);
    }

    /**
     * Check if the path is valid. A valid path is absolute (starts with a '/')
     * or relative (doesn't start with '/'), and contains none or more elements.
     * A path may not end with '/', except for the root path. Elements itself must
     * be at least one character long.
     *
     * @param path the path
     * @return {@code true} iff the path is valid.
     */
    public static boolean isValid(String path) {
        if (path.isEmpty() || denotesRootPath(path)) {
            return true;
        } else if (path.charAt(path.length() - 1) == '/') {
            return false;
        }
        char last = 0;
        for (int index = 0, len = path.length(); index < len; index++) {
            char c = path.charAt(index);
            if (c == '/') {
                if (last == '/') {
                    return false;
                }
            }
            last = c;
        }
        return true;
    }

    private static boolean isAbsolutePath(String path) {
        return !path.isEmpty() && path.charAt(0) == '/';
    }

    private static boolean denotesRootPath(String path) {
        return "/".equals(path);
    }
}

Related

  1. isAbsolute(final String path)
  2. isAbsolute(String aPath)
  3. isAbsolute(String path)
  4. isAbsolute(String path)
  5. isAbsolutePath(String filename)
  6. isAbsolutePath(String path)
  7. isAbsolutePath(String path)
  8. isAbsolutePath(String path)