在JavaWeb项目的定时任务中获取相对路径

在JavaWeb项目定时任务中无法使用以下方法获取路径

request.getContextPath()

public String getPosition(String name,String telNumber,HttpServletRequest request) throws Exception {

    System.out.println("类文件路径:" + request.getContextPath() + "\\WEB-INF\\classes");
    System.out.println("类文件路径:" + RequestContext.class.getResource("/").getFile() + "BaseStationconfig.xml");
}

可以用以下方法获得相对路径

public static PlayMusic getDoorBaseStationMac() throws Exception {
    WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
    ServletContext servletContext = webApplicationContext.getServletContext();
    System.out.println("文件路径:" + "/WEB-INF/classes/BaseStationconfig.xml");
    FileInputStream xmlInputStream = (FileInputStream) servletContext.getResourceAsStream("/WEB-INF/classes/BaseStationconfig.xml");
}

文件在工程目录位置见下图


猜你喜欢

转载自blog.csdn.net/maowendi/article/details/80922477