Fetch file from specific directory where jar file is placed

巧了我就是萌 提交于 2020-01-16 19:38:06

问题


I want to fetch a text file from the directory where my jar file is placed.

Assuming my desktop application 'foo.jar' file is placed in d:\ in an installation of Windows. There is also a test.txt file in the same directory which I want to read when 'foo.jar' application is running. How can fetch that particular path in my 'foo.jar' application? In short I want to fetch the path of my 'foo.jar' file where it is placed.


回答1:


Note, that actual code does depend on actual class location within your package, but in general it could look like:

URL root = package.Main.class.getProtectionDomain().getCodeSource().getLocation();
String path = (new File(root.toURI())).getParentFile().getPath();
...
// handle file.txt in path



回答2:


Most JARs are loaded using a URLClassLoader that remembers the codesource from where the JAR has been loaded. You may use this knowledge to obtain the location of the directory from where the JAR has been loaded by the JVM. You can also use the ProtectionDomain class to get the CodeSource (as shown in the other answer; admittedly, that might be better).

The location returned is often of the file: protocol type, so you'll have to remove this protocol identifier to get the actual location. Following is a short snippet that performs this activity; you might want to build in more error checking and edge case detection, if you need to use it in production:

public String getCodeSourceLocation() {
        ClassLoader contextClassLoader = CurrentJARContext.class.getClassLoader();
        if(contextClassLoader instanceof URLClassLoader)
        {
            URLClassLoader classLoader = (URLClassLoader)contextClassLoader;
            URL[] urls = classLoader.getURLs();
            String externalForm = urls[0].toExternalForm();
            externalForm = externalForm.replaceAll("file:\\/", "");
            externalForm = externalForm.replaceAll("\\/", "\\" + File.separator);
            return externalForm;
        }
        return null;
    }



回答3:


I found the shortest answer of my own question.
String path = System.getProperty("user.dir");



来源:https://stackoverflow.com/questions/6247845/fetch-file-from-specific-directory-where-jar-file-is-placed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!