Absolute File path Web application
While working on web based application and you are trying to find absolute path of deployed application using with you could set properties file from class path. I will you how to get it using small project:
- Maven project structure:
- As you see in above project we have file name: Sample.xml and we need to find it path at run time as below:
package com.javahonk.controller; import java.io.File; import java.util.Properties; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class SpringMVCController { @RequestMapping(value = "/firstPage") public String firstPage(ModelMap model) { //Get absolute path String absolutePath=new File(Thread.currentThread().getContextClassLoader().getResource("").getFile()).getParentFile().getParentFile().getPath(); System.out.println(absolutePath); //Use properties file to keep file path as below: Properties prop = new Properties(); //Sample.xml file will be inside /WEB-INF/classes folder prop.put("file.resource.loader.path", absolutePath+"/WEB-INF/classes"); //Example 2: Get full path if you know the file name String path = Thread.currentThread().getContextClassLoader().getResource("Sample.xml").getPath(); File file = new File(path); String absoluteFilePath = file.getAbsolutePath(); System.out.println(absoluteFilePath); return "index"; } }
- Output:
- For more information find relative and absolute path java please see this tutorial
Download Project: SpringMVCRESTFulService