Java项目中资源路径总结

本文详细解析了客户端和服务端路径配置的方法,包括相对路径和绝对路径的使用场景,特别强调了不同路径配置对应用的影响。同时,介绍了多种获取资源文件的方式,并对比了不同方式的优缺点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

项目中使用路径时的写法

1.客户端路径 ==> 给浏览器用的路径,如下:
			<form action="/Day08-request/AServlet" >
			<a href="/Day08-request/AServlet" >
			<img src="/Day08-request/AServlet" >
			response.sendRedirect("/Day08-request/AServlet")
			Refresh:3;url=/Day08-request/AServlet

路径写法:
带"/" : “/” > 相对于 主机.
例如: 表单所在页面路径为
> http://localhost:8080/Day08-request/login.jsp ==>
“/” 代表http://localhost:8080/

不带"/":(开发中一定不要出现不带"/"的情况).代表从当前目录找.
例如: 表单所在页面路径为==>
http://localhost:8080/Day08-request/info/login.jsp ==>
代表 http://localhost:8080/Day08-request/info/

2.服务器端路径 ==> 服务器端使用的路径,如下:
	<url-pattern> /AServlet  ==>
	http://localhost:8080/Day08-request/AServlet
	request.getRequestDispatcher("/AServlet") ==> 
	http://localhost:8080/Day08-request/AServlet

路径写法:
带”/” : 相对于项目. “/”==>http://localhost:8080/Day08-request/
不带”/”: 不存在这种情况 (服务器端使用的路径必须带”/”).

获取资源时的路径写法

1. ServletContext
	servletContext中关于路径的获得必须以“/”开头,"/"相对于 WebRoot(项目根)下
			getRealPath  ==> 通过相对路径获得绝对路径
			getResourceAsStream ==> 根据相对路径获得指定资源流
2. Class.getResourceAsStream(String path)
	相对路径分为两种情况
					//1: 加"/"  ==> 相对的是classes目录
					//2: 不加"/" ==> 相对的是本类当前目录
			this.getClass().getResourceAsStream("students.xml");
3. Class.getClassLoader.getResourceAsStream(String path)
	只有一个相对路径 ==> 加"/"不加"/"都是相对于 classes目录 this.getClass().getClassLoader().getResourceAsStream("students.xml");

2019最新总结

  1. 以下写法参数中的“/”代表classpath根目录,能正常获取classes(即classpath)目录下config文件夹中的配置文件: InputStream in = PropertiesUtil.class.getResourceAsStream("/config/bigdata.properties");
  2. 以下写法参数中没有以“/”开头,IDE运行时默认是classpath根目录,能正常获取编译后target中classes(即classpath)目录下config文件夹中的配置文件(注意:当以jar运行时,jar包中没有classes目录,classpath默认为jar包的根目录):InputStream in = PropertiesUtil.class.getClassLoader().getResourceAsStream(“config/bigdata.properties”);
  3. InputStream in = PropertiesUtil.class.getResourceAsStream(“config/bigdata.properties”); 这种写法不推荐,默认是当前类(PropertiesUtil)所在包的目录,实际项目中不会用!!
  4. InputStream in = PropertiesUtil.class.getClassLoader().getResourceAsStream("/config/bigdata.properties"); 这种写法会报错,使用getClassLoader()时参数前面不能加“/”!!
  5. 以上4种写法主要是区别class、getClassLoader和“/”的搭配所代表的意思即可,都需要把配置文件放在项目内部,即打包后无法在外面灵活修改,因为classpath位于jar包中的(即jar包的根目录)!!

若要想在jar包同级目录放配置文件,在项目中可使用如下写法:

 InputStream in = new FileInputStream(new File(System.getProperty("user.dir") + "/config/bigdata.properties"));
 或者: InputStream in = new FileInputStream(new File("config/bigdata.properties"));
 或者: InputStream in = new FileInputStream(new File("./config/bigdata.properties"));

也可以使用另一种写法:

String p1 = PropertiesUtil.class.getProtectionDomain().getCodeSource().getLocation().getPath();
p1 = java.net.URLDecoder.decode(p1, "UTF-8");	//转换处理中文及空格
打包前运行输出:p1=/D:/dev/idea-workspace/worktest/target/classes/
打成jar包后输出:p1=/D:/dev/idea-workspace/worktest/target/xxx-jar-with-dependencies.jar

其中“/D:/dev/idea-workspace/worktest/target/”就是jar包所在目录

实践:

package utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.Properties;

/**
 * Created by zhangbn on 2019/12/12.
 */
public class PropertiesUtil {

    public static Logger logger = LoggerFactory.getLogger(PropertiesUtil.class);
    private static Properties props;

    static {
        loadProps();
    }

    /**
     * @Description 加载属性配置文件
     * @Params []
     * @Return
     * @Author zhangbn
     */
    synchronized static private void loadProps() {
        if (null == props) {
            logger.debug("show: 开始加载bigdata.properties文件内容.......");
            props = new Properties();
            InputStream in = null;
            try {
                //show: user.dir路径--------------------------------------------:D:\Workspace\V2235_bigdata\vehicle\vehiclejobs
                logger.info("show: user.dir路径--------------------------------------------:" + System.getProperty("user.dir"));

                //1.IDE运行:项目的根目录;   2.jar运行:jar的同级目录
//                in = new FileInputStream(new File(System.getProperty("user.dir") + "/src/main/resources/bigdata.properties"));

                //1.IDE运行:项目的根目录;   2.jar运行:jar的同级目录
//                in = new FileInputStream(new File("bigdata.properties"));

                //1.IDE运行:项目的resources目录(也是编译后target中classes目录,即classpath);     2.jar运行:jar包的根目录
                in = PropertiesUtil.class.getClassLoader().getResourceAsStream("bigdata.properties");
                props.load(in);
            } catch (FileNotFoundException e) {
                logger.error("properties文件未找到");
            } catch (IOException e) {
                logger.error("出现IOException");
            } finally {
                try {
                    if (null != in) {
                        in.close();
                    }
                } catch (IOException e) {
                    logger.error("properties文件流关闭出现异常");
                }
            }
            logger.debug("show: 加载bigdata.properties文件内容完成");
            logger.debug("show: properties文件内容:" + props);
        }
    }

    /**
     * @Description 通过key获取value
     * @Params [key]
     * @Return
     * @Author zhangbn
     */
    public static String getProperty(String key) {
        if (null == props) {
            loadProps();
        }
        if (null != System.getenv(key.replaceAll("\\.", "_").toUpperCase())) {
            return System.getenv(key.replaceAll("\\.", "_").toUpperCase()).trim();
        }
        return props.getProperty(key).trim();
    }

    /**
     * @Description 通过key获取value, 并指定默认值
     * @Params [key, defaultValue]
     * @Return
     * @Author zhangbn
     */
    public static String getProperty(String key, String defaultValue) {
        if (null == props) {
            loadProps();
        }
        if (null != System.getenv(key.replaceAll("\\.", "_").toUpperCase())) {
            return System.getenv(key.replaceAll("\\.", "_").toUpperCase()).trim();
        }
        return props.getProperty(key, defaultValue).trim();
    }

    public static void main(String[] args) {
        System.out.println(getProperty("vehicle.hive.nocturnal.dt"));
    }

}

2020最新总结

SpringBoot获取src/main/resource路径下的文件的两种方式:不打jar包 / 打成jar包

在这里插入图片描述

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值