Java (maven web app), getting full file path for file in resources folder?

Rick picture Rick · Aug 25, 2011 · Viewed 16.7k times · Source

I'm working with a project that is setup using the standard Maven directory structure so I have a folder called "resources" and within this I have made a folder called "fonts" and then put a file in it. I need to pass in the full String file path (of a file that is located, within my project structure, at resources/fonts/somefont.ttf) to an object I am using, from a 3rd party library, as below, I have searched on this for a while but have become a bit confused as to the proper way to do this. I have tried as below but it isn't able to find it. I looked at using ResourceBundle but that seemed to involve making an actual File object when I just need the path to pass into a method like the one below (don't have the actual method call in front of me so just giving an example from my memory):

FontFactory.somemethod("resources/fonts/somefont.ttf");

I had thought there was a way, with a project with standard Maven directory structure to get a file from the resource folder without having to use the full relative path from the class / package. Any advice on this is greatly appreciated.

I don't want to use a hard-coded path since different developers who work on the project have different setups and I want to include this as part of the project so that they get it directly when they checkout the project source.

This is for a web application (Struts 1.3 app) and when I look into the exploded WAR file (which I am running the project off of through Tomcat), the file is at:

<Exploded war dir>/resources/fonts/somefont.ttf

Answer

BobG picture BobG · Aug 25, 2011

Code:

import java.io.File;
import org.springframework.core.io.*;

public String getFontFilePath(String classpathRelativePath) {
    Resource rsrc = new ClassPathResource(classpathRelativePath);
    return rsrc.getFile().getAbsolutePath();
}

In your case, classpathRelativePath would be something like "/resources/fonts/somefont.ttf".