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:/myworkspace/freemarkertest/webroot/WEB-INF/classes/util
E:/myworkspace/freemarkertest/webroot/WEB-INF/images/logo.gif
E:/myworkspace/freemarkertest/webroot
*/