Relative file path java web application

Relative file path java web application

If you are working on web application and want fetch absolute file which is inside your deployed war file in any server at run time please see below:

  • Example project structure:

Relative file path java web application

  • Now export war file and structure of war file is below:

Relative file path java web application

  • You will have to add below code to get file absolute path from server:
String path = Thread.currentThread().getContextClassLoader().getResource("Sample.xml").getPath();
	File file = new File(path);
	String absoluteFilePath = file.getAbsolutePath();
	System.out.println(absoluteFilePath);
  • Complete file:
package com.javahonk.controller;

import java.io.File;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;


@Controller
public class SpringMVCController {
	
	private static final Logger logger = Logger.getLogger(SpringMVCController.class);
	
	@RequestMapping(value = "/firstPage")
	public String firstPage(ModelMap model) {
		
		logger.info("Log4j info is working");
		
		String path = Thread.currentThread().getContextClassLoader().getResource("Sample.xml").getPath();
		File file = new File(path);
		String absoluteFilePath = file.getAbsolutePath();
		System.out.println(absoluteFilePath);
        model.addAttribute("message", "Spring MVC RESTFul Service");
		
		return "index";		
	}
	


}
  • Now I will run this project inside tomcat server in eclipse and it shows below file path inside server:

Relative file path java web application

 

For more information method please see oracle documentation of Thread class here

download Download Project: SpringMVCRESTFulService

Leave a Reply

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