Absolute File path Web application

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:

Absolute File path Web application

  • 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:

Absolute File path Web application

  •  For more information find relative and absolute path java please  see this tutorial

download Download Project:  SpringMVCRESTFulService

Leave a Reply

Your email address will not be published. Required fields are marked *