原理:通过class的getResource方法来获取class所在的目录,经过简单处理后达到获取目标文件目录的目的。
package com.cnksi.webrootpath;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Properties;
public class PropertiesUitl {
public static void main(String[] args) {
System.out.println(getWebRootPath()); // 根路径
System.out.println(getProperties("web.xml")); // 获取指定文件的内容
}
/**
* 获取WEB-INF下的指定文件
* @param fileName
* @return
*/
public static Properties getProperties(String fileName) {
Properties prop = new Properties(); // 从配置文件中获取信息
try {
// 获取当前类加载的根目录,如:E:/project/jfinal_demo/WebRoot/WEB-INF/
String path = PropertiesUitl.getWebInfPath() + File.separator + fileName;
FileInputStream fis = new FileInputStream(new File(path)); // 把文件读入文件输入流,存入内存中
prop.load(fis); //加载文件流的属性
} catch (IOException e) {
e.printStackTrace();
}
return prop;
}
/**
* 获取项目的WEB-INF目录
* @return
*/
private static String getWebInfPath() {
return getWebRootPath() + File.separator + "WEB-INF";
}
/**
* @return E:/project/jfinal_demo/WebRoot;
* 获取项目的WebRoot目录
* 原理:通过class的getResource方法来获取class所在的目录;
* 此处:String.class.getResource("/") 是返回class文件(此处为String对应的class文件)所在的顶级目录,
* 即:/E:/project/jfinal_demo/build/classes/;
*/
public static String getWebRootPath() {
try {
String path = String.class.getResource("/").toURI().getPath();
String project_path = new File(path).getParentFile().getParentFile().getCanonicalPath();
return project_path + File.separator + "WebRoot";
} catch (URISyntaxException e) { e.printStackTrace();
} catch (IOException e) { e.printStackTrace(); }
return "";
}
/**
* 三种获取路径方式的不同结果:getPath、getAbsolutePath、getCanonicalPath
* @throws IOException
*/
public void getPath() throws IOException {
{
System.out.println("------默认相对路径,取得路径不同-----");
File f = new File("..\\src\\file");
System.out.println(f.getPath());
System.out.println(f.getAbsolutePath());
System.out.println(f.getCanonicalPath());
System.out.println("------默认相对路径,取得路径不同-----");
File f2 = new File(".\\src\\file");
System.out.println(f2.getPath());
System.out.println(f2.getAbsolutePath());
System.out.println(f2.getCanonicalPath());
System.out.println("------默认绝对路径,取得路径相同-----");
File f3 = new File("C:\\src\\file");
System.out.println(f3.getPath());
System.out.println(f3.getAbsolutePath());
System.out.println(f3.getCanonicalPath());
// 执行结果为:
// ------默认相对路径,取得路径不同-----
// ..\src\file
// C:\workspace\Tip\..\src\file
// C:\workspace\src\file
// ------默认相对路径,取得路径不同-----
// .\src\file
// C:\workspace\Tip\.\src\file
// C:\workspace\Tip\src\file
// ------默认绝对路径,取得路径相同-----
// C:\src\file
// C:\src\file
// C:\src\file
//
// 比较可以得到
// getPath()返回的是构造方法里的路径,不做任何处理
// getAbsolutePath()返回的是 user.dir+getPath(),也就是执行路径加上构造方法中的路径
// getCanonicalPath()返回的是将符号完全解析的路径,也就是全路径
}
}
}