JAVA method to get the absolute path to a file

  • 2020-04-01 03:40:09
  • OfStack

This article illustrates a JAVA method for obtaining the absolute path to a file. Share with you for your reference. The specific implementation method is as follows:

/**
* Gets the value of a class class The absolute path to the file. This class could be JDK Its own class, also can be a user - defined class, or a third - party development package in the class.
* As long as the class can be loaded in this program, it can be located class The absolute path to the file.
*
* @param cls
*            Of an object Class attribute
* @return This class of class The absolute path to the file location. Returns if there is no definition of the class null .
*/
private String getPathFromClass(Class cls) throws IOException {
     String path = null;
     if (cls == null) {
       throw new NullPointerException();
     }
     URL url = getClassLocationURL(cls);
     if (url != null) {
       path = url.getPath();
       if ("jar".equalsIgnoreCase(url.getProtocol())) {
         try {
           path = new URL(path).getPath();
         }
         catch (MalformedURLException e) {
         }
         int location = path.indexOf("!/");
         if (location != -1) {
           path = path.substring(0, location);
         }
       }
       File file = new File(path.replaceAll("%20"," "));
       path = file.getCanonicalPath();
     }
     return path;
   }
   /**
    * For class class File location URL . This method is the most basic method of the class and can be called by other methods.
    */
   private URL getClassLocationURL(final Class cls) {
     if (cls == null) {
       throw new IllegalArgumentException("class that input is null");
     }
     URL result = null;
     final String clsAsResource = cls.getName().replace('.', '/').concat(".class");
     final ProtectionDomain pd = cls.getProtectionDomain();
     if (pd != null) {
       final CodeSource cs = pd.getCodeSource();
       if (cs != null) {
         result = cs.getLocation();
       }
       if (result != null) {
         if ("file".equals(result.getProtocol())) {
           try {
             if (result.toExternalForm().endsWith(".jar")|| result.toExternalForm().endsWith(".zip")) {
               result = new URL("jar:".concat(result.toExternalForm()).concat("!/").concat(clsAsResource));
             }
             else if (new File(result.getFile()).isDirectory()) {
               result = new URL(result, clsAsResource);
             }
           }
           catch (MalformedURLException ignore) {
           }
         }
       }
     }
     if (result == null) {
       final ClassLoader clsLoader = cls.getClassLoader();
       result = clsLoader != null ? clsLoader.getResource(clsAsResource): ClassLoader.getSystemResource(clsAsResource);
     }
     return result;
}

I hope this article has been helpful to your Java programming.


Related articles: