Java Path Convert To filePathToClassNameOrNull(String filePathWithExtension)

Here you can find the source of filePathToClassNameOrNull(String filePathWithExtension)

Description

Return the class name of the given java source or class file as suggested by the file path, or null if the class name could not be determined

License

Apache License

Parameter

Parameter Description
filePathWithExtension a parameter

Declaration

public static String filePathToClassNameOrNull(String filePathWithExtension) 

Method Source Code

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

public class Main {
    /**//from  w  w  w .  jav a2s .  c o m
     * Return the class name of the given java source or class file as suggested by the file path, or null if the class name could not be determined
     * 
     * @param filePathWithExtension
     * @return
     */
    public static String filePathToClassNameOrNull(String filePathWithExtension) {
        if (filePathWithExtension.endsWith(".java") || filePathWithExtension.endsWith(".class")) {
            String classPath = stripExtension(filePathWithExtension);
            String className = filePathToClassPath(classPath);
            return className;
        }
        return null;
    }

    public static String stripExtension(String path) {
        int dot = path.lastIndexOf('.');
        if (dot != -1) {
            return path.substring(0, dot);
        }
        return path;
    }

    private static String filePathToClassPath(String path) {
        path = toForwardSlashes(path);
        if (path.charAt(0) == '/') {
            path = path.substring(1);
        }
        return path.replace('/', '.');
    }

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

Related

  1. filePathToClassPath(String path)
  2. filePathToJavaBinaryName(final String filePath, final String separator)
  3. filePathToPackagePathOrNull(String path)
  4. filePathToUrl(String filePath)