In Java, you often locate some files, in order to allow programs to be independent of the physical location, the relative path is used. However, the use of relative paths in Java will always encounter some troublesome problems, which is the problem of which reference. Because we usually use relative paths, it is always relatively related to the current working directory, but sometimes it is not the case. For example, to use a relative path in a development kit, it does not know the path when the development package is called by other programs, and especially in a web application, it is difficult to determine a relative path of a file throughout the app.
So the best way to use the relative path is to let the path relative to the reference matter is my development package or my application itself, the best is the class file of the class in the package. As long as you know the absolute path of a Class file, you can use the relative path to locate any other files with its reference.
In order to achieve this idea, I wrote this PATH class. This class provides two static public methods, a location for locating the class file, and the other with a class as a reference to locate a relative path. With these two methods, we can completely do not pay attention to the current work path of the app, and find any files according to your own position. For example, when writing a functional development package, you can do not need to call the path of this development package, but only according to the location of the development kit itself, this is very good to implement encapsulation, will file The path processing is completely enclosed within the development package itself.
The following is the source code of the PATH class:
* Create a date 2004-11-22 * * Change the generated file template to * Window> Preferences> Java> Code> Code and Comment * / package mytools;
Import java.io.file; import java.io.ioException; import java.net.malformedurlexception; import java.Net.ur; import java.security.codesource; import java.security.protectionDomain
/ ** * @Author by month * * This class provides some ways to position according to the class of Class files according to the class. * / Public class path {/ ** * Get the absolute path where a class of Class files is located. This class can be a class of JDK itself or a user-defined class, or a class in a third-party development package. * As long as it is a class that can be loaded in this program, it can be positioned to the absolute path of its Class file. * * @Param CLS * A class attribute of an object * @return's absolute path of the Class file location of this class. Returns NULL if this class is not defined. * / Public static 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 (mALFORMEDUREXCEPTION E) {} int location = path. Indexof ("! /"); if (location! = -1) {path = path.substring (0, location);}} file file = new file (path); path = file.getcanonicalPath ();} returnophful }
/ ** * This method can obtain an absolute path to the file or directory by the relative path of a class of Class files. It is usually difficult to locate a relative path in the program, especially in the B / S application. * With this method, we can locate a relative path according to the location of our class files. * For example: a TXT file relative to the path of the program's Test class file is ../../Resource/test.txt, * So use this method Path.GetFullPathRelateClass ("../../ resource / test.txt "Test.class) * The result obtained is the absolute path of the TXT file in the system. * @Param RelatedPath * relative path * @Param CLS * Used to locate the @returN relative path corresponding to the absolute path * @Throws ioException * Because this method will query the file system, there may be IO exception * / public static String getFullPathRelateClass (String relatedPath, Class cls) throws IOException {String path = null; if (relatedPath == null) {throw new NullPointerException ();} String clsPath = getPathFromClass (cls); File clsFile = new File (clsPath); String tempPath = clsfile.getParent () file.seParent RelatedPath; file file = new file (temppath); path = file.getcanonicalPath (); return path;} / ** * Gets the URL of class's class file location. This method is the most basic method of this class for other methods. * / Private static URL getClassLocationURL (final Class cls) {if (cls == null) throw new IllegalArgumentException. ( "Null input: cls"); URL result = null; final String clsAsResource = cls.getName () replace ( '. ',' / '). Concat (".class"); Final ProtectionDomain Pd = CLS.GetProtectionDomain (); // java.lang.class contract does not specify // if' PD 'Can Ever Be null; // IT Is Not The Case for Sun's Implementations, // But Guard Against Null // Just In Case: IF (Pd! = NULL) = Pd.getCodesource (); // 'cs' can be null depending ON // The ClassLoader Behavior: IF (CS! = Null) Result = cs.getlocation ();
IF (Result! = NULL) {// Convert a code source location INTO / / A FULL CASS FILE LOCATION // for Some Common Cases: IF ("File" .Equals (result.getProtocol ()) {TRY {IF Result.ToExternalForm (). Endswith (". jar") || result.toExternalForm (). Endswith (". zip")) Result = new URL ("JAR:". Concat (Result.ToExternalForm ()). Concat "! /") .Concat (clsrasource)); else if (result.getfile ()). Isdirectory ()) Result = new url (result, clsasource);} catch (mALFORMEDUREXCEPTION IGNORE) {}}}} IF (result == null) {// try to find 'cls' definition as a resource; // this is not // Document. d to be legal, but Sun's // implementations seem to // allow this:!? final ClassLoader clsLoader = cls.getClassLoader (); result = clsLoader = null clsLoader.getResource (clsAsResource): ClassLoader.getSystemResource (clsAsResource);} return RESULT;
Public static void main (string [】 args) {try {system.out.println (getpathfromclass (path.class)); system.out.println (GetFullPathRelateClass ("../ Test / Abc / ..", Path.class ));} Catch (exception e) {E.PrintStackTrace ();}}}