Post description: it is very easy to use. It is convenient to process the path of the file to be generated when Velocity and FreeMarker generate the file.
Package util;
Import java. io. File;
Import java. io. IOException;
Import java.net. URI;
Import java.net. URISyntaxException;
/***//**
* @ Author <a href = "mailto: maryang@live.cn" mce_href = "Maryangmailto: maryang@live.cn"> Maryang </a>
* @ Version $ Revision: 1.0 $
* This class provides some methods for locating based on the class file location of the class.
*/
Public class PathUtil {
/***//**
* Obtain the absolute path of a Class.
* @ Param clazz Class Object
* @ Return Class absolute path
*/
Public static String getPathByClass (Class clazz ){
String path = null;
Try {
URI uri = clazz. getResource (""). toURI ();
File file = new File (uri );
Path = file. getCanonicalPath ();
} Catch (URISyntaxException e ){
E. printStackTrace ();
} Catch (IOException e ){
E. printStackTrace ();
}
Return path;
}
/***//**
* Obtain the absolute path of an object relative to a Class.
* @ Param clazz Class Object
* @ Param relativePath relative path of the Class Object
* @ Return absolute path of the file
*/
Public static String getFilePathByClass (Class clazz, String relativePath ){
String filePath = null;
String clazzPath = getPathByClass (clazz );
StringBuffer sbPath = new StringBuffer (clazzPath );
SbPath. append (File. separator );
SbPath. append (relativePath );
File file = new File (sbPath. toString ());
Try {
FilePath = file. getCanonicalPath ();
} Catch (IOException e ){
E. printStackTrace ();
}
Return filePath;
}
Public static void main (String [] args ){
Try {
System. out. println (getPathByClass (PathUtil. class ));
System. out. println (getFilePathByClass (PathUtil. class, ".../images/logo.gif "));
System. out. println (getFilePathByClass (PathUtil. class ,"../../../"));
} Catch (Exception e ){
E. printStackTrace ();
}
}
}
/*
E: MyWorkspaceFreeMarkerTestWebRootWEB-INFclassesutil
E: MyWorkspaceFreeMarkerTestWebRootWEB-INFimageslogo.gif
E: MyWorkspaceFreeMarkerTestWebRoot
*/