Java工程与WEB工程读取项目下文件的区别

Java工程读取项目下文件,使用的是相对路径,相对JVM路径

private void readFile() throws FileNotFoundException, IOException {
    //获取文件输入流
    InputStream is = new FileInputStream("src/db.properties");
    Properties properties = new Properties();
    properties.load(is);

    String driverClass = properties.getProperty("driverClass");
    String url = properties.getProperty("url");
    String username = properties.getProperty("username");
    String password = properties.getProperty("password");

}

WEB工程读取项目下文件,相对与JVM路径,此时JVM已交给Tomcat管理

private void readFile(HttpServletRequest request) throws FileNotFoundException, IOException {
    ServletContext context = request.getSession().getServletContext();
    //方法一.直接获取文件输入流
    /*InputStream is = context.getResourceAsStream("/WEB-INF/classes/db.properties");*/
    //方法二.获得该文件的磁盘绝对路径
    String realPath = context.getRealPath("/WEB-INF/classes/db.properties");
    InputStream is = new FileInputStream(realPath);
    
    Properties properties = new Properties();
    properties.load(is);

    String driverClass = properties.getProperty("driverClass");
    String url = properties.getProperty("url");
    String username = properties.getProperty("username");
    String password = properties.getProperty("password");
}

request.getSession().getServletContext() 获取的是Servlet容器对象,相当于tomcat容器了。

getRealPath("/") 获取实际路径,“/”指代项目根目录,所以返回的是项目在容器中的实际发布运行的根路径。

使用类加载器读取文件

public static void readFile() throws IOException{
    // 使用类的加载器来读取文件.
    // 类的加载器用来加载class文件,将class文件加载到内存.
    InputStream is = ReadFileUtils.class.getClassLoader().getResourceAsStream("db.properties");
    Properties properties = new Properties();
    properties.load(is);

    String driverClass = properties.getProperty("driverClass");
    String url = properties.getProperty("url");
    String username = properties.getProperty("username");
    String password = properties.getProperty("password");
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值