jfinal源码

关于jfinal中PathKit的源码分析

/**
 * new File("..\path\abc.txt") 中的三个方法获取路径的方法
 * 1: getPath() 获取相对路径,例如   ..\path\abc.txt
 * 2: getAbslutlyPath() 获取绝对路径,但可能包含 ".." 或 "." 字符,例如  D:\otherPath\..\path\abc.txt
 * 3: getCanonicalPath() 获取绝对路径,但不包含 ".." 或 "." 字符,例如  D:\path\abc.txt
 */
public class PathKit {
	
	private static String webRootPath;
	private static String rootClassPath;
	
	@SuppressWarnings("rawtypes")
	public static String getPath(Class clazz) {
		String path = clazz.getResource("").getPath();
		return new File(path).getAbsolutePath();
	}
	
	public static String getPath(Object object) {
		String path = object.getClass().getResource("").getPath();
		return new File(path).getAbsolutePath();
	}
	
	public static String getRootClassPath() {
		if (rootClassPath == null) {
			try {
				String path = PathKit.class.getClassLoader().getResource("").toURI().getPath();
				rootClassPath = new File(path).getAbsolutePath();
			}
			catch (Exception e) {
				String path = PathKit.class.getClassLoader().getResource("").getPath();
				rootClassPath = new File(path).getAbsolutePath();
			}
		}
		return rootClassPath;
	}
	
	public void setRootClassPath(String rootClassPath) {
		PathKit.rootClassPath = rootClassPath;
	}
	
	public static String getPackagePath(Object object) {
		Package p = object.getClass().getPackage();
		return p != null ? p.getName().replaceAll("\\.", "/") : "";
	}
	
	public static File getFileFromJar(String file) {
		throw new RuntimeException("Not finish. Do not use this method.");
	}
	
	public static String getWebRootPath() {
		if (webRootPath == null)
			webRootPath = detectWebRootPath();
		return webRootPath;
	}
	
	public static void setWebRootPath(String webRootPath) {
		if (webRootPath == null)
			return ;
		
		if (webRootPath.endsWith(File.separator))
			webRootPath = webRootPath.substring(0, webRootPath.length() - 1);
		PathKit.webRootPath = webRootPath;
	}
	
	private static String detectWebRootPath() {
		try {
			String path = PathKit.class.getResource("/").toURI().getPath();
			return new File(path).getParentFile().getParentFile().getCanonicalPath();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	/*
	private static String detectWebRootPath() {
		try {
			String path = PathKit.class.getResource("/").getFile();
			return new File(path).getParentFile().getParentFile().getCanonicalPath();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
	*/
}

 
通过对jfinal的PathKit源码分析,该类主要是项目相关路径的获取,同时也可衍生出各种不同的路径方法
Java路径中的空格问题
1、 XXX.class.getResource("/").getPath();
    XXX.class.getResource("/").getFile();
    XXX.class.getClassLoader().getResource("").getPath();
    Thread.currentThread().getContextClassLoader().getResource("").getPath();等多种相似方式获得的路径,不能被FileReader()和FileWriter()直接应用,原因是URL对空格,特殊字符(%,#,[]等)和中文进行了编码处理。如果文件中XXX.class.getResource("/").getPath();必须以"/"开头然后再加文件名,而XXX.class.getClassLoader().getResource("").getPath();不用加"/"可以直接添加文件名。

路径中包含空格时,如果空格变为"%20"有如下处理方法:
1)使用repaceAll("%20",' ')替换,但只能解决空格问题,如果路径中包含其他特殊字符和中文就不能解决问题。
2)使用URLDecoder.decode(str,"UTF-8")解码,但是只能解决一部分,若路径中含有+,也是不能解决的,原因是URL并不是完全用URLEncoder.encode(str,"UTF-8")编码的,+号被解码后,则变成空格。
3)解决所有的问题,用URLTest.class.getClassLoader().getResource("").toURI().getPath();,但是需要处理URISyntaxException异常,比较麻烦一些。

2、new URL();的参数可以为正确的URI,或者为URI格式的字符串;若字符串是非完整的URI格式,则创建失败。java.net.URI返回的路径中的空格以“空格”的形式出现方法为Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath();但是Thread.currentThread().getContextClassLoader().getResource("").toURI().toString();则会以“%20”的形式出现。java.net.URL返回的一切路径中的空格都是以“%20”的形式出现。URL/URI返回的路径分隔符都是“/”(控制台输出"/")。


3、new File(String filePath);接受正确URI格式的参数和带“空格”(非%20)的正确相对/绝对字符串路径,否则即使给的路径是正确的也会出现找不到文件的异常。File返回的路径分隔符都为“\”(控制台输出"\"),对于存在的文件返回的路径字符串,空格都以"空格"出现,而不存在的路径new出的file,getPath()返回的路径中的空格,仍是new File(String filePath)的参数中原有的形式,即若filePath中是空格的getPath()返回的仍是空格,是“%20”的仍是“%20”。File.toURI() 会将file的路径名中的“空格”转化为“%20”,然后在路径前加protocol:"file:/",而File.toURL()只会在file路径 前简单的加上protocol:"file:/",而不会将“空格”转化为“%20”,原来的无论是“空格”还是“%20”都只会原样保留。


实际使用中遇到的问题总结如下:
1、相对路径(即相对于当前用户目录的相对路径)均可通过以下方式获得(不论是一般的java项目还是web项目) String relativelyPath=System.getProperty("user.dir"); 对于一般的java项目中的文件是相对于项目的根目录,而对于web项目中的文件路径,可能是服务器的某个路径,同时不同的web服务器也不同 (tomcat是相对于 tomcat安装目录\bin)。为此,个人认为,在web项目中,最好不要使用“相对于当前用户目录的相对路径”。然而默认情况下,java.io 包中的类总是根据当前用户目录来分析相对路径名。此目录由系统属性 user.dir 指定,通常是 Java 虚拟机的调用目录。这就是说,在使用java.io包中的类时,最好不要使用相对路径。否则,虽然在SE程序中可能还算正常,但是到了EE程序中,可能会出现问题。

2、web项目根目录获取
1)建立一个servlet,在其init()方法中添加如下代码
ServletContext context = this.getServletContext();
String strs = context.getRealPath("/");
2)利用httpServletRequest,得到相应的项目路径
String pathUrl = request.getSession().getServletContext().getRealPath("/");

猜你喜欢

转载自dalan-123.iteye.com/blog/2235940