1. 程式人生 > >java web 專案 真實 路徑 獲取 windows linux 系統 通用工具類

java web 專案 真實 路徑 獲取 windows linux 系統 通用工具類

package com.web.tools;

import java.io.File;

public class GetWebProjectRealPathTool {
	/**
	 * 獲取專案在服務其中的真實路徑的工具類
	 * 這是在web專案中,獲取專案實際路徑的最佳方式,在windows和linux系統下均可正常使用
	 */
	
	//獲取專案的根路徑
	public static String classPath = GetWebProjectRealPathTool.class.getClassLoader().getResource("/").getPath();
	//對專案的根路徑進行解析,拿到專案路徑
	
	public static String getRootPath() {
		String rootPath = "";
		//windows下
		if("\\".equals(File.separator)){
			System.out.println("windows");
		rootPath = classPath.substring(1,classPath.indexOf("/WEB-INF/classes"));
		rootPath = rootPath.replace("/", "\\");
		}
		//linux下
		if("/".equals(File.separator)){
			System.out.println("linux");
		rootPath = classPath.substring(0,classPath.indexOf("/WEB-INF/classes"));
		rootPath = rootPath.replace("\\", "/");
		}
		return rootPath;
		}
}