Home > Java, Programming > Locate your files in Java

Locate your files in Java

April 30th, 2010 jmguilla

This post is also available in: French

I am sure you have already tried to locate files when running methods in a framework or in a web container… If so, you have experimented how tough it is… Forget the MyClass.class.getResourceAsStream() method, the solution rely on the following:

import java.net.URL;
import java.security.ProtectionDomain;
public class TestPath {
	/** @param args */
	public static void main(String[] args) {
	    ProtectionDomain protectionDomain = TestPath.class.getProtectionDomain();
	    URL location = protectionDomain.getCodeSource().getLocation();

Now I use that two simple lines of code, my life is different ;)

Categories: Java, Programming Tags: ,
Comments are closed.