Sameek Mishra
Sameek Mishra

Reputation: 9384

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?

Upvotes: 49

Views: 205613

Answers (15)

qingmu
qingmu

Reputation: 482

I think System.getProperty("java.class.path") and System.getProperty("path.separator") are better schemes. eg:

private final static String JAR_SUFFIX = ".jar";

public static String getJarRuntimePath(){
        String javaClassPath = System.getProperty("java.class.path");
        String pathSeparator = System.getProperty("path.separator");
        if(javaClassPath.contains(pathSeparator)){
            javaClassPath = filePath.substring(0,filePath.indexOf(pathSeparator));
        }else if (javaClassPath.endsWith(JAR_SUFFIX)) {
            javaClassPath = filePath.substring(0, filePath.lastIndexOf(File.separator) + 1);
        }
        File serverLocalConfig = new File(javaClassPath);
        return serverLocalConfig.getAbsolutePath();
}

Upvotes: 0

Chris
Chris

Reputation: 389

I think everyone's missing a key problem with this.

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

The servlet instance could be on one of the arbitrarily many nodes and doesn't technically require a file system at all.

In Java EE containers for example the application could be loaded from a database or even a directory server. Different parts of the application can also be running on different nodes. Access to the world outside the application is provided by the application server.

Use java.util.logging or Apache Commons Logging if you have to maintain compatibility with legacy log4j. Tell the application server where the log file is supposed to go.

Upvotes: 0

Chameleon
Chameleon

Reputation: 2136

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.

    Upvotes: -1

  • Lpia IT
    Lpia IT

    Reputation: 1

    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

    Upvotes: -1

    Chhaileng Peng
    Chhaileng Peng

    Reputation: 2516

    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";
    }
    

    Upvotes: 0

    Disapamok
    Disapamok

    Reputation: 1475

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

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

    Upvotes: 2

    BullyWiiPlaza
    BullyWiiPlaza

    Reputation: 19185

    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.

    Upvotes: 7

    Mihir Patel
    Mihir Patel

    Reputation: 412

    /*****************************************************************************
         * 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()
    

    Upvotes: 1

    user207421
    user207421

    Reputation: 310850

    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().

    Upvotes: 38

    Nacho Cougil
    Nacho Cougil

    Reputation: 562

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

    Upvotes: 11

    Gary
    Gary

    Reputation: 7257

    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.

    Upvotes: -2

    Sudantha
    Sudantha

    Reputation: 16194

    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.

    Upvotes: 4

    Andrew Thompson
    Andrew Thompson

    Reputation: 168815

    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.

    Upvotes: 1

    Bozho
    Bozho

    Reputation: 597016

    new File(".").getAbsolutePath()
    

    Upvotes: 1

    Qwerky
    Qwerky

    Reputation: 18405

    Try;

    String path = new File(".").getCanonicalPath();
    

    Upvotes: 59

    Related Questions