How to get the current working directory in Java?

前端 未结 22 3113
时光说笑
时光说笑 2020-11-21 07:16

I want to access my current working directory using java.

My code :

 String current = new java.io.File( \".\" ).getCanonicalPath();
        System.ou         


        
相关标签:
22条回答
  • 2020-11-21 07:52

    Code :

    public class JavaApplication {
      public static void main(String[] args) {
        System.out.println("Working Directory = " + System.getProperty("user.dir"));
      }
    }
    

    This will print the absolute path of the current directory from where your application was initialized.


    Explanation:

    From the documentation:

    java.io package resolve relative pathnames using current user directory. The current directory is represented as system property, that is, user.dir and is the directory from where the JVM was invoked.

    0 讨论(0)
  • 2020-11-21 07:53

    assume that you're trying to run your project inside eclipse, or netbean or stand alone from command line. I have write a method to fix it

    public static final String getBasePathForClass(Class<?> clazz) {
        File file;
        try {
            String basePath = null;
            file = new File(clazz.getProtectionDomain().getCodeSource().getLocation().toURI().getPath());
            if (file.isFile() || file.getPath().endsWith(".jar") || file.getPath().endsWith(".zip")) {
                basePath = file.getParent();
            } else {
                basePath = file.getPath();
            }
            // fix to run inside eclipse
            if (basePath.endsWith(File.separator + "lib") || basePath.endsWith(File.separator + "bin")
                    || basePath.endsWith("bin" + File.separator) || basePath.endsWith("lib" + File.separator)) {
                basePath = basePath.substring(0, basePath.length() - 4);
            }
            // fix to run inside netbean
            if (basePath.endsWith(File.separator + "build" + File.separator + "classes")) {
                basePath = basePath.substring(0, basePath.length() - 14);
            }
            // end fix
            if (!basePath.endsWith(File.separator)) {
                basePath = basePath + File.separator;
            }
            return basePath;
        } catch (URISyntaxException e) {
            throw new RuntimeException("Cannot firgue out base path for class: " + clazz.getName());
        }
    }
    

    To use, everywhere you want to get base path to read file, you can pass your anchor class to above method, result may be the thing you need :D

    Best,

    0 讨论(0)
  • 2020-11-21 07:55

    Using Windows user.dir returns the directory as expected, but NOT when you start your application with elevated rights (run as admin), in that case you get C:\WINDOWS\system32

    0 讨论(0)
  • 2020-11-21 07:55

    This is my silver bullet when ever the moment of confusion bubbles in.(Call it as first thing in main). Maybe for example JVM is slipped to be different version by IDE. This static function searches current process PID and opens VisualVM on that pid. Confusion stops right there because you want it all and you get it...

      public static void callJVisualVM() {
        System.out.println("USER:DIR!:" + System.getProperty("user.dir"));
        //next search current jdk/jre
        String jre_root = null;
        String start = "vir";
        try {
            java.lang.management.RuntimeMXBean runtime =
                    java.lang.management.ManagementFactory.getRuntimeMXBean();
            String jvmName = runtime.getName();
            System.out.println("JVM Name = " + jvmName);
            long pid = Long.valueOf(jvmName.split("@")[0]);
            System.out.println("JVM PID  = " + pid);
            Runtime thisRun = Runtime.getRuntime();
            jre_root = System.getProperty("java.home");
            System.out.println("jre_root:" + jre_root);
            start = jre_root.concat("\\..\\bin\\jvisualvm.exe " + "--openpid " + pid);
            thisRun.exec(start);
        } catch (Exception e) {
            System.getProperties().list(System.out);
            e.printStackTrace();
        }
    }
    
    0 讨论(0)
  • 2020-11-21 07:56

    Current working directory is defined differently in different Java implementations. For certain version prior to Java 7 there was no consistent way to get the working directory. You could work around this by launching Java file with -D and defining a variable to hold the info

    Something like

    java -D com.mycompany.workingDir="%0"
    

    That's not quite right, but you get the idea. Then System.getProperty("com.mycompany.workingDir")...

    0 讨论(0)
  • 2020-11-21 07:58

    I've found this solution in the comments which is better than others and more portable:

    String cwd = new File("").getAbsolutePath();
    

    Or even

    String cwd = Paths.get("").toAbsolutePath();
    
    0 讨论(0)
提交回复
热议问题