关于文件路径的获取类, 备忘一下
public class PathUtils {
private static Log logger = LogFactory.getLog(PathUtils.class);
/**
* 针对文件跟class在目录下, 根据文件名取得文件绝对路径
*
* @param clazz
* @param fileName
* @return
*/
public static String getAbsolutePath(Class<?> clazz, String fileName) {
try {
return clazz.getResource(fileName).getFile();
} catch (Exception e) {
throw new FileNoFoundException(log(fileName, e));
}
}
private static String log(String fileName, Exception e) {
String message = "获取文件失败!fileName=" + fileName;
logger.warn(message, e);
return message;
}
/**
* 针对文件在class根目录下, 根据文件名取得文件绝对路径
*
* @param clazz
* @param fileName
* @return
*/
public static String getAbsolutePath(String fileName) {
try {
return PathUtils.class.getClassLoader().getResource(fileName).getFile();
} catch (Exception e) {
String message = log(fileName, e);
throw new FileNoFoundException(message);
}
}
}
本文介绍了一种通过类路径获取文件绝对路径的方法。提供了两种方式:一种是针对与类在同一目录下的文件,另一种是针对位于类根目录下的文件。这两种方法都通过异常处理确保了路径获取的可靠性。

被折叠的 条评论
为什么被折叠?



