How to get the current working directory in Java?

前端 未结 22 3119
时光说笑
时光说笑 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: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,

提交回复
热议问题