1. 程式人生 > >Java獲取根目錄

Java獲取根目錄

package com.ecenter.tools;

import java.io.File;

public class UrlPathUitl {
	
	public static String getPath(){
		ClassLoader classLoader = Thread.currentThread()
				.getContextClassLoader();
		if (classLoader == null) {
			classLoader = ClassLoader.getSystemClassLoader();
		}
		java.net.URL url = classLoader.getResource("");
		String ROOT_CLASS_PATH = url.getPath() + "/";
		File rootFile = new File(ROOT_CLASS_PATH);
		String WEB_INFO_DIRECTORY_PATH = rootFile.getParent() + "/";
		File webInfoDir = new File(WEB_INFO_DIRECTORY_PATH);
		// 這裡 SERVLET_CONTEXT_PATH 就是WebRoot的路徑
		String SERVLET_CONTEXT_PATH = webInfoDir.getParent() + "/";
		System.out.println(SERVLET_CONTEXT_PATH);
		return SERVLET_CONTEXT_PATH;
	}

}