Java Path Convert To filePathToPackagePathOrNull(String path)

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

Description

Return the package name part of the given file path or null if no package name could be determined

License

Apache License

Declaration

public static String filePathToPackagePathOrNull(String path) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

public class Main {
    /**// w w w .  j  a  va2  s  .  c o  m
     * Return the package name part of the given file path or null if no package name could be determined
     */
    public static String filePathToPackagePathOrNull(String path) {
        path = toForwardSlashes(path);
        if (path.charAt(0) == '/') { //e.g   /Foo/Bar - > Foo/Bar, Foo/Bar --> Foo/Bar
            path = path.substring(1);
        }
        int last = path.lastIndexOf('/');
        if (last == -1) { //no package part
            return null;
        }
        String pkg = path.substring(0, last); //e.g  Foo/Bar - > Foo
        pkg = pkg.replace('/', '.');
        if (pkg.length() == 0) {
            return null;
        }
        return pkg;
    }

    public static String toForwardSlashes(String path) {
        if (path == null) {
            return null;
        }
        return path.replace('\\', '/');
    }
}

Related

  1. filePathToClassNameOrNull(String filePathWithExtension)
  2. filePathToClassPath(String path)
  3. filePathToJavaBinaryName(final String filePath, final String separator)
  4. filePathToUrl(String filePath)
  5. pathTo(String filename)
  6. pathTo(String ref)
  7. pathToAdjacencyList(final int[] path, final int[] adjacencyList)