Java web项目中获取WebRoot目录下的文件

例如要获取项目中MSJH.TTF的目录:
Java web项目中获取WebRoot目录下的文件_第1张图片

public static String getFontPath(){
     
        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);  
        String SERVLET_CONTEXT_PATH = webInfoDir.getParent() + "/";  
        //这里 SERVLET_CONTEXT_PATH 就是WebRoot的路径  
        String path = SERVLET_CONTEXT_PATH + "fonts/MSJH.TTF";  
        path = path.replaceAll("%20", " "); 
        return path;
	}

你可能感兴趣的:(Java,java)