Java获取项目中的文件

Java获取WebRoot路径下的文件

    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() + "/";   
    String path = SERVLET_CONTEXT_PATH + "/" + 文件路径;  
    path = path.replaceAll("%20", " ");  
    File f = new File(path);

获取src下的fileurl.properties文件路径

this.getClass().getResource("/fileurl.properties").getPath()

【this.getClass().getResourceAsStream("/"+Basic.dll);】----jar中的class获取jar内部的资源文件,该文件打包成jar前放置在src目录下

如果文件和读取类在同一个包下,把“/”去掉【this.getClass().getResourceAsStream(Basic.dll);】

获取webRoot下的service文件夹路径

request.getSession().getServletContext().getRealPath("/service");

解决路径中包含空格

URLDecoder.decode(this.getClass().getResource("/fileurl.properties").getPath(),"utf-8")

 

获取jar同级目录下的文件:例如System.getProperty("user.dir")+java.io.File.separator+“文件名”

参考链接:https://www.cnblogs.com/lmq-1048498039/p/5568034.html

猜你喜欢

转载自blog.csdn.net/qq_26975307/article/details/84066812