[java] How to get the real path of Java application at runtime?

I am creating a Java application where I am using log4j. I have given the absolute path of configuration log4j file and also an absolute path of generated log file(where this log file are generated). I can get the absolute path of a Java web application at run time via:

String prefix =  getServletContext().getRealPath("/");

but in the context of a normal Java application, what can we use?

This question is related to java filepath

The answer is


It is better to save files into a sub-directory of user.home than wherever the app. might reside.

Sun went to considerable effort to ensure that applets and apps. launched using Java Web Start cannot determine the apps. real path. This change broke many apps. I would not be surprised if the changes are extended to other apps.


If you want to use this answer: https://stackoverflow.com/a/4033033/10560907

You must add import statement like this:

import java.io.File;

in very beginning java source code.

like this answer: https://stackoverflow.com/a/43553093/10560907


/*****************************************************************************
     * return application path
     * @return
     *****************************************************************************/
    public static String getApplcatonPath(){
        CodeSource codeSource = MainApp.class.getProtectionDomain().getCodeSource();
        File rootPath = null;
        try {
            rootPath = new File(codeSource.getLocation().toURI().getPath());
        } catch (URISyntaxException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }           
        return rootPath.getParentFile().getPath();
    }//end of getApplcatonPath()

And what about using this.getClass().getProtectionDomain().getCodeSource().getLocation()?


I use this method to get complete path to jar or exe.

File pto = new File(YourClass.class.getProtectionDomain().getCodeSource().getLocation().toURI());

pto.getAbsolutePath());

I have a file "cost.ini" on the root of my class path. My JAR file is named "cost.jar".

The following code:

  • If we have a JAR file, takes the directory where the JAR file is.
  • If we have *.class files, takes the directory of the root of classes.

try {
    //JDK11: replace "UTF-8" with UTF_8 and remove try-catch
    String rootPath = decode(getSystemResource("cost.ini").getPath()
            .replaceAll("(cost\\.jar!/)?cost\\.ini$|^(file\\:)?/", ""), "UTF-8");
    showMessageDialog(null, rootPath, "rootpath", WARNING_MESSAGE);
} catch(UnsupportedEncodingException e) {}

Path returned from .getPath() has the format:

  • In JAR: file:/C:/folder1/folder2/cost.jar!/cost.ini
  • In *.class: /C:/folder1/folder2/cost.ini

    Every use of File, leads on exception, if the application provided in JAR format.


  • If you want to get the real path of java web application such as Spring (Servlet), you can get it from Servlet Context object that comes with your HttpServletRequest.

    @GetMapping("/")
    public String index(ModelMap m, HttpServletRequest request) {
        String realPath = request.getServletContext().getRealPath("/");
        System.out.println(realPath);
        return "index";
    }
    

    Since the application path of a JAR and an application running from inside an IDE differs, I wrote the following code to consistently return the correct current directory:

    import java.io.File;
    import java.net.URISyntaxException;
    
    public class ProgramDirectoryUtilities
    {
        private static String getJarName()
        {
            return new File(ProgramDirectoryUtilities.class.getProtectionDomain()
                    .getCodeSource()
                    .getLocation()
                    .getPath())
                    .getName();
        }
    
        private static boolean runningFromJAR()
        {
            String jarName = getJarName();
            return jarName.contains(".jar");
        }
    
        public static String getProgramDirectory()
        {
            if (runningFromJAR())
            {
                return getCurrentJARDirectory();
            } else
            {
                return getCurrentProjectDirectory();
            }
        }
    
        private static String getCurrentProjectDirectory()
        {
            return new File("").getAbsolutePath();
        }
    
        private static String getCurrentJARDirectory()
        {
            try
            {
                return new File(ProgramDirectoryUtilities.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()).getParent();
            } catch (URISyntaxException exception)
            {
                exception.printStackTrace();
            }
    
            return null;
        }
    }
    

    Simply call getProgramDirectory() and you should be good either way.


    If you're talking about a web application, you should use the getRealPath from a ServletContext object.

    Example:

    public class MyServlet extends Servlet {
        public void doGet(HttpServletRequest req, HttpServletResponse resp) 
                  throws ServletException, IOException{
             String webAppPath = getServletContext().getRealPath("/");
        }
    }
    

    Hope this helps.


    It isn't clear what you're asking for. I don't know what 'with respect to the web application we are using' means if getServletContext().getRealPath() isn't the answer, but:

    • The current user's current working directory is given by System.getProperty("user.dir")
    • The current user's home directory is given by System.getProperty("user.home")
    • The location of the JAR file from which the current class was loaded is given by this.getClass().getProtectionDomain().getCodeSource().getLocation().

    The expression

    new File(".").getAbsolutePath();
    

    will get you the current working directory associated with the execution of JVM. However, the JVM does provide a wealth of other useful properties via the

    System.getProperty(propertyName); 
    

    interface. A list of these properties can be found here.

    These will allow you to reference the current users directory, the temp directory and so on in a platform independent manner.


    new File(".").getAbsolutePath()