summaryrefslogtreecommitdiffstats
path: root/Master/Agile Software Development/TestApp/src/testapp/Locate.java
blob: 49f96a960814b9898cb74426402442add2b376c2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/*
 * 
 */

package testapp;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.logging.*;

/**@author McDowell*/
public class Locate {
  
  /**
   * Returns the URL of a given class.
   * @param c    a non-null class
   * @return    the URL for that class
   */
  public static URL getUrlOfClass(Class c) {
    if(c==null) {
      throw new NullPointerException();
    }
    String className = c.getName();
    String resourceName = className.replace('.', '/') + ".class";
    ClassLoader classLoader = c.getClassLoader();
    if(classLoader==null) {
      classLoader = ClassLoader.getSystemClassLoader();
    }
    URL url = classLoader.getResource(resourceName);
    return url;
  }
  
  /**
   * Finds the location of a given class file on the file system.
   * Throws an IOException if the class cannot be found.
   * <br>
   * If the class is in an archive (JAR, ZIP), then the returned object
   * will point to the archive file.
   * <br>
   * If the class is in a directory, the base directory will be returned
   * with the package directory removed.
   * <br>
   * The <code>File.isDirectory()</code> method can be used to
   * determine which is the case.
   * <br>
   * @param c    a given class
   * @return    a File object
   * @throws IOException
   */
  public static File getClassLocation(Class c) throws IOException, FileNotFoundException {
    if(c==null) {
      throw new NullPointerException();
    }
    
    String className = c.getName();
    String resourceName = className.replace('.', '/') + ".class";
    ClassLoader classLoader = c.getClassLoader();
    if(classLoader==null) {
      classLoader = ClassLoader.getSystemClassLoader();
    }
    URL url = classLoader.getResource(resourceName);
    
    String szUrl = url.toString();
    if(szUrl.startsWith("jar:file:")) {
      try {
        szUrl = szUrl.substring("jar:".length(), szUrl.lastIndexOf("!"));
        URI uri = new URI(szUrl);
        return new File(uri);
      } catch(URISyntaxException e) {
        throw new IOException(e.toString());
      }
    } else if(szUrl.startsWith("file:")) {
      try {
        szUrl = szUrl.substring(0, szUrl.length() - resourceName.length());
        URI uri = new URI(szUrl);
        return new File(uri);
      } catch(URISyntaxException e) {
        throw new IOException(e.toString());
      }
    }
    
    throw new FileNotFoundException(szUrl);
  }
  
}