Java Root Directory Get getRoot()

Here you can find the source of getRoot()

Description

get Root

License

Open Source License

Return

the path of the directory the executable file of this application is located in. If an error occurred, this method will return the working directory specified in the key " user.dir " in the System properties.

Declaration

public static String getRoot() 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.io.File;

public class Main {
    private static String rootPath;

    /**/*from www . j  av a2s  .  c o  m*/
     * @return the path of the directory the executable file of this application is located in. If
     * an error occurred, this method will return the working directory specified in the key
     * "{@code user.dir}" in the {@code System} properties.
     */
    public static String getRoot() {
        // Determine root dir
        //===================
        if (rootPath == null) {
            try {
                // Get root path
                //==============
                File rootDir = new File(ClassLoader.getSystemClassLoader()
                        .getResource(".").toURI().getPath());
                rootPath = rootDir.getAbsolutePath();

                // Jump higher if not in root dir
                //===============================
                if (rootPath.endsWith("bin")) {
                    rootPath = rootPath.substring(0, rootPath.length()
                            - "bin".length());
                } else if (rootPath.endsWith("target" + File.separator
                        + "classes")) {
                    rootPath = rootPath
                            .substring(
                                    0,
                                    rootPath.length()
                                            - ("target" + File.separator + "classes")
                                                    .length());
                } else {
                    rootPath = rootPath + File.separator;
                }
            } catch (Exception e) {
                rootPath = System.getProperty("user.dir");
            }
        }
        return (rootPath);
    }
}

Related

  1. getRoot()
  2. getRoot()
  3. getRoot()
  4. getRoot()
  5. getRoot()
  6. getRoot(File child)
  7. getRoot(File file)
  8. getRoot(File file)